gpt4 book ai didi

c - 递增 struct* 中 int* 指向的值

转载 作者:行者123 更新时间:2023-11-30 19:11:13 25 4
gpt4 key购买 nike

我有一个像这样定义的结构:

typedef struct {
char* name;
int* numVotes;
} candidate;

像这样分配:

 candidate* Person[10]; 
int i;
for (i = 0; i < 10; i++) {
Person[i] = malloc(sizeof(candidate));
Person[i]->name = malloc(25*sizeof(char));
Person[i]->numVotes = malloc(sizeof(int));
}

尝试增加存储在 numVotes 中的值,如下所示:

int v;
scanf("%d",&v);
while (v != 0) {
switch (v) {
case 1 :
Person[0]->numVotes++;
break;
case 2 :
Person[1]->numVotes++;
break;
case 3 :
Person[2]->numVotes++;
break;
case 4 :
Person[3]->numVotes++;
break;
case 5 :
Person[4]->numVotes++;
break;
case 6 :
Person[5]->numVotes++;
break;
case 7 :
Person[6]->numVotes++;
break;
case 8 :
Person[7]->numVotes++;
break;
case 9 :
Person[8]->numVotes++;
break;
case 10 :
Person[9]->numVotes++;
break;
default :
printf("Spoiled vote\n");
break;

}
scanf("%d",&v);
}

但是,在打印结果时,我相信这会增加 numVotes 指向的内存地址。此外,当我尝试释放内存时,它给了我无效的指针。如何仅增加 Person[i]->numVotes 指向的值(而不是内存地址)?谢谢。

最佳答案

我同意您不应该使用 *int 而应该使用 int 。但如果你必须这样做

++(*Person[2]->numVotes);
....
printf(%d, *Person[2]->numVotes);

而且你似乎忘了将初始化归零,你总是会得到垃圾值,所以添加

memset(Person[i]->numVotes , 0, sizeof (int));

在你的for循环中

关于c - 递增 struct* 中 int* 指向的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40495724/

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