gpt4 book ai didi

c - 函数看不到结构内部结构的字段

转载 作者:行者123 更新时间:2023-11-30 16:39:11 24 4
gpt4 key购买 nike

所以,我必须做库发送 IPv4 数据包(没有带有准备好的 header 的库),问题是我在使用函数时无法访问结构内部结构中的字段,尽管 Eclipse 没有看到错误,但提示没有显示是有可能的。

结构:

struct packet{
struct ipv4hdr * iphdr;
struct icmphdr * icmphdr;
char * data;
};
struct ipv4hdr{
u_int8_t version_length;
u_int8_t type;
u_int16_t total_length;
u_int16_t id;
u_int16_t frag_off;
u_int8_t ttl;
u_int8_t protocol;
u_int16_t checksum;
u_int32_t source;
u_int32_t destination;
};

函数指针(这是要求,两者都有效):

struct packet *(*packetCreate)() = dlsym(lib, "createPacket");
void (*setIP)(struct packet *, u_int8_t, u_int8_t, u_int16_t, char*, u_int8_t, char*) = dlsym(lib, "prepareIP");

创建结构体数据包:

struct packet * createPacket(){
struct packet * pack= malloc(sizeof(struct packet));
return pack;
}

现在,在 main 中调用字段确实会显示可能的字段:

struct packet * pack = packetCreate();
pack->iphdr->(CTRL+space displays all the fields) //and eclipse automatically corrects all the . to ->

同时,在使用提示时调用函数上创建的指针时不会显示字段,这会导致段错误(核心转储):

void prepareIP(struct packet * packet, u_int8_t length, u_int8_t type, u_int16_t id, char* destination, u_int8_t ttl, char *data){

packet->iphdr->type = type; //it is not treated by error, though any field causes crash
//meanwhile hint
packet->iphdr->(CTRL+space gets)ipv4hdr;

}

再次出现的问题是为什么我无法在函数内调用指向原始结构的特定字段以及如何在该函数内执行此操作

最佳答案

您似乎忘记为 struct ipv4hdr * iphdr; 分配空间

但这也许不是您想要的。你真的希望 iphdr 成为你的结构中的指针吗?如果它是结构的一部分,那就更有意义了,如下所示:

struct packet{
struct ipv4hdr iphdr; // notice that we do not use pointers here!
struct icmphdr icmphdr; // this looks curious to me - we have either an IP or an ICMP package, why both headers in the same package?
char * data;
};

关于c - 函数看不到结构内部结构的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47156066/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com