gpt4 book ai didi

c - 如何理解段错误?

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

我第一次尝试在 C 中使用结构和指针。而且我真的不明白为什么我总是遇到段错误,即使程序编译得很好。我也对内存分配感到困惑。我们是否每次都在内存分配中使用强制转换?

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



#define HOW_MANY 7

char *names[HOW_MANY]= {"Adam", "James", "Matt", "Affleck", "Benedict", "Kayne",
"Evans"};
int ages[HOW_MANY]= {22, 24, 46, 56, 21, 32, 30};

/* declare your struct for a person here */
typedef struct{
char name[HOW_MANY];
int age;
}person;


static void insert(person *people[], char *name, int age)
{
static int nextfreeplace = 0;
// Allocating memory here
people = malloc(sizeof(person));

if (people == NULL) {
printf("Couldn't allocate memory");
exit(-1);
}

strcpy((*people[nextfreeplace]).name,name);

(*people[nextfreeplace]).age = age;

nextfreeplace++;
}

int main(int argc, char **argv)
{
person *people[HOW_MANY];

for (int i = 0; i < HOW_MANY ; i++)
{
insert (people, names[i], ages[i]);
}

/* print the people array here*/
for (int i = 0; i < HOW_MANY ; i++)
{

printf("The person's name is %s and the age is %d.\n",(*people[i]).name,(*people[i]).age);
}

for (int i = 0; i < HOW_MANY ; i++)
{
free(people[i]);
}

return 0;
}

这是分配内存的正确方法吗?

最佳答案

在您的 C 代码中保持相同的逻辑

调用 insert 提供指向您要分配内存的位置的指针,即 people 数组中指针位置的地址;在 main 函数 for 循环中:

insert (&people[i], names[i], ages[i]);

因此在插入

static void insert(person **people, char *name, int age)
{
*people = malloc(sizeof(person));

if (*people == NULL) {
printf("Couldn't allocate memory");
exit(-1);
}

strcpy((*people)->name,name);

(*people)->age = age;
}

关于c - 如何理解段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40392135/

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