gpt4 book ai didi

c - 带指针的结构体数组

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

我正在学习 C.我编写了代码,错误是“传递‘strcpy’的参数 1 使指针来自整数而不进行强制转换”。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct humans{
sname[20];
}human;


int main(){
human *person=(human *)malloc(sizeof(human)*1);

int i,k,z;
for(i=0;i<5;i++){
person=(human *)realloc(person,sizeof(human)*(i+1));
strcpy(*person[i].sname , "john");
}


for(i=0;i<5;i++){
printf("%s",*person[i].sname);
}
return 0;
}

我想使用 malloc/realloc。

最佳答案

如果您有 *person[i].sname,则需要 person[i].sname 来代替。当您在其前面放置 * 时,您会强制数组衰减为指向其第一个元素的指针,当取消引用时,该指针会为您提供第一个元素的值。

另外:

    person=(human *)realloc(person,sizeof(human)*1);

这个1应该是i + 1

关于c - 带指针的结构体数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53709904/

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