Search code examples
c++pointerspass-by-reference

How to access a member of a struct which is passed into a function as pointer to pointer parameter?


I have a struct:

typedef struct addrinfo
{
    int ai_flags;
    int ai_family;
    int ai_socktype;
    int ai_protocol;
    size_t ai_addrlen;
    char *ai_canonname;
    struct sockaddr *ai_addr;
    struct addrinfo *ai_next;
} ADDRINFOA, *PADDRINFOA;

And I defined a function which accepts a pointer to pointer of type struct addrinfo and returns the value via "pointer reference"

void getAddress(addrinfo **addr){
     addr->ai_addr->sa_data = "0.0.0.0";   //sa_data is a member of ai_addr
}

I called a function getAddress using the following codes:

addrinfo *IPAddr = new addrinfo();
IPAddr->ai_addr = new sockaddr(); 
getAddress(&IPAddr);

I get an error:

error: request for member 'ai_addr' in '* IPAddr ', which is of pointer type 'addrinfo*' (maybe you meant to use '->' ?)
*IPAddr ->ai_addr->sa_data[14] = {"10.10.10.10"};

Solution

  • You need to dereference addr (*addr) to get the addrinfo* back and you can't assign a C string directly to to the char[] sa_data, you need to copy the C string into place.

    Example:

    #include <algorithm>
    #include <iterator>
    
    void getAddress(addrinfo **addr){
        static const char zeroes[] = "0.0.0.0";
        std::copy_n(zeroes, std::size(zeroes), (*addr)->ai_addr->sa_data);
    }
    

    Note: According to C++ Operator Precedence * (dereferencing) has lower precedence than -> (member access) so we need to wrap (*addr) in parentheses in order to dereference addr in (*addr)->ai_addr->sa_data.