PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, July 5, 2022

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

 July 05, 2022     c++, pass-by-reference, pointers     No comments   

Issue

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.



Answered By - Ted Lyngmo
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing