gpt4 book ai didi

c - 为具有指针成员的指针结构分配内存

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

我正在尝试使用具有指针成员的结构指针来读取和打印。所以我试图读取和打印双结构指针数组。我尝试了以下操作,但它给我错误消息“访问冲突写入位置(内存中的某处)”

如何为此动态分配内存?

#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif

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

typedef struct template{
char *name;
int *birthdate;
int *phoneNum;

} detailsOf;

void inputValue(detailsOf **person, int maxSize);

int main() {

detailsOf **person;
int maxSize = 0, menu = 0;

printf("Max:");
scanf("%d", &maxSize);


person = (detailsOf **)malloc(maxSize * sizeof(detailsOf **));
if (person == NULL) {
printf("Failed to allocate");
exit(0);
}
for (int i = 0; i < maxSize; i++) {
person[i]->name = (char *)calloc(21, sizeof(char ));
person[i]->birthdate = (int *)calloc(8, sizeof(int ));
person[i]->phoneNum = (int *)calloc(16, sizeof(int ));
}

inputValue(person, maxSize);

for (int i = 0; i < maxSize; i++) {
free(person[i]);
for (int j = 0; j < 21; j++) {
free(person[i]->name[j]);
}
for (int j = 0; j < 15; j++) {
free(person[i]->phoneNum[j]);
}
for (int j = 0; j < 8; j++) {
free(person[i]->birthdate[j]);
}
}
return 0;
}
void inputValue(detailsOf **person, int maxSize) {
for (int i = 0; i < maxSize; i++) {
printf("Name of %d", i + 1);
scanf("%s", person[i]->name);
for (int j = 0; j < 8; j++) {
printf("Birth %d:", i + 1);
scanf("%d", person[i]->birthdate[j]);
}
for (int k = 0; k < 8; k++) {
printf("Phone %d:", i + 1);
scanf("%d", person[i]->phoneNum[k]);
}
}
printf("SUCCESS\n");
}

最佳答案

person = (detailsOf **)malloc(maxSize * sizeof(detailsOf **));

应该是

person = malloc(maxSize * sizeof(detailsOf *));

然后,分配的内存用于保存指向 detailsOf 的指针,但您永远不会为每个 detailsOf 分配内存

for(int i=0; i<maxSize; i++)
{
person[i]=malloc(sizeof(detailsOf));
}

您还应该释放内存

for (int i = 0; i < maxSize; i++)
{
free(person[i]->name);
free(person[i]->phoneNum);
free(person[i]->birthdate);
free(person[i]);
}
free(person);

请记住,释放时只需将 free 调用与 malloc 调用相匹配。

关于c - 为具有指针成员的指针结构分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50500915/

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