如何访问作为指向指针参数的指针传递给函数的结构成员?
How to access a member of a struct which is passed into a function as pointer to pointer parameter?
我有一个结构:
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;
并且我定义了一个函数,它接受一个指向 struct addrinfo 类型指针的指针和 returns 通过“指针引用”
的值
void getAddress(addrinfo **addr){
addr->ai_addr->sa_data = "0.0.0.0"; //sa_data is a member of ai_addr
}
我使用以下代码调用了函数 getAddress:
addrinfo *IPAddr = new addrinfo();
IPAddr->ai_addr = new sockaddr();
getAddress(&IPAddr);
我收到一个错误:
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"};
addr->ai_addr
等同于 (*addr).ai_addr
但 (*addr)
returns 是指向 addrinfo
的指针。这就是错误消息告诉您的内容。您不能从指针访问成员。您必须取消引用 addr
两次,例如(*addr)->ai_addr
或 (**addr).ai_addr
.
您需要取消引用 addr
(*addr
) 才能取回 addrinfo*
并且您不能将 C 字符串直接分配给 char[]
sa_data
,你需要将C字符串复制到位。
示例:
#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);
}
注意:根据 C++ Operator Precedence *
(取消引用)的优先级低于 ->
(成员访问),因此我们需要将 (*addr)
括在括号中以便在 (*addr)->ai_addr->sa_data
.
中取消引用 addr
我有一个结构:
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;
并且我定义了一个函数,它接受一个指向 struct addrinfo 类型指针的指针和 returns 通过“指针引用”
的值void getAddress(addrinfo **addr){
addr->ai_addr->sa_data = "0.0.0.0"; //sa_data is a member of ai_addr
}
我使用以下代码调用了函数 getAddress:
addrinfo *IPAddr = new addrinfo();
IPAddr->ai_addr = new sockaddr();
getAddress(&IPAddr);
我收到一个错误:
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"};
addr->ai_addr
等同于 (*addr).ai_addr
但 (*addr)
returns 是指向 addrinfo
的指针。这就是错误消息告诉您的内容。您不能从指针访问成员。您必须取消引用 addr
两次,例如(*addr)->ai_addr
或 (**addr).ai_addr
.
您需要取消引用 addr
(*addr
) 才能取回 addrinfo*
并且您不能将 C 字符串直接分配给 char[]
sa_data
,你需要将C字符串复制到位。
示例:
#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);
}
注意:根据 C++ Operator Precedence *
(取消引用)的优先级低于 ->
(成员访问),因此我们需要将 (*addr)
括在括号中以便在 (*addr)->ai_addr->sa_data
.
addr