gpt4 book ai didi

c - 获取结构体数组内结构体的值

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

typedef struct{
int number;
char name[100];
} Apple

typedef struct{
Apple *apple;
int bit[2];
} AppleArray;

int main(){
AppleArray *aArray;
loadApple(&aArray);
}

loadApple(AppleArray **aArray){
*aArray = NULL;
for(i=0; i<100; i++){
*aArray = realloc(*aArray, (i+1) * sizeof(AppleArray));

/*SEGFAULT here*/
aArray[i]->apple = NULL;

for(j=0; j<2; j++){
aArray[i]->apple = realloc(aArray[i]->apple, sizeof(Apple) * (j+1))
}
}

}

我想要一个具有特定大小的AppleArray。每个 AppleArray 将有两个 Apple。但是,当我将 NULL 分配给 aArray[i]->apple 时,出现段错误。那里有什么问题?

编辑:

loadApple(AppleArray **aArray){
*aArray = malloc(100 * sizeof(AppleArray));
for(i=0; i<100; i++){

/*SEGFAULT here*/
aArray[i]->apple = NULL;

for(j=0; j<2; j++){
aArray[i]->apple = realloc(aArray[i]->apple, sizeof(Apple) * (j+1))
}
}
}

最佳答案

您可以调用realloc()仅在由先前的内存分配函数返回给您的地址上,例如 malloc()calloc()否则它会给你未定义的行为

C99 标准 7.20.3.4-3:realloc 函数:

void *realloc(void *ptr, size_t size);

If ptr is a null pointer, the realloc function behaves like the malloc function for the specified size. Otherwise, if ptr does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to the free or realloc function, the behavior is undefined.

关于c - 获取结构体数组内结构体的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10547441/

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