gpt4 book ai didi

c - C中Struct的恼人问题

转载 作者:太空宇宙 更新时间:2023-11-04 01:26:30 24 4
gpt4 key购买 nike

struct Users{
int id;
char msg[];
};

int nUsers;

struct Users users[10];

void connectUser(struct Users user){
if(nUsers<10){
for(int i=0;i<10;i++){
if(users[i]==NULL){
users[i]=user;
printf("user %d connected!\n", user.id);
nUsers++;
}
}
}else
printf("number of users reached!\n");
}

那是我的代码,当我尝试编译时,出现错误:

[s3450124@csitprdap01 ~]$ gcc -std=c99 socketserver.c -o socketserver
socketserver.c: In function ‘connectUser’:
socketserver.c:24: error: invalid operands to binary == (have ‘struct Users’ and ‘void *’)
socketserver.c:21: note: The ABI of passing struct with a flexible array member has changed in GCC 4.4
socketserver.c: In function ‘disconnectUser’:
socketserver.c:37: error: incompatible types when assigning to type ‘struct Users’ from type ‘void *’

每次我尝试编译时,都会出现这些错误。你们能帮帮我吗?

最佳答案

当 i = 0 时,users[i] 的类型是 Struct Users。它不是指针,因此不能具有 NULL 值。这就是您的编译器所提示的。您正在检查该值是否为 NULL 而不是。您只在比较指针时检查 NULL。

// you already check here that you do not exceed bounds of array - 10
for(int i=0;i<10;i++){
users[i]=user;
etc

关于c - C中Struct的恼人问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30139039/

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