gpt4 book ai didi

使用数组 char* 的 C 程序崩溃

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

我想构建一个允许插入姓名并打印出来的程序。但程序一开始就崩溃。

这是我的主课:

void main(int argc, char *argv[]) {
int* n = (int*) malloc(sizeof(int));
char listStudent[100][31];
char* name = (char*) malloc(31);
int id;
*n = 0;
addStudent("John ABC", listStudent, n);
addStudent("David Davinci", listStudent, n);
}

以及一些要调用的函数

void addStudent(char name[31], char listName[][31], int *pn) {
int id;
id = findName(name, listName, *pn);
if(id < 0) {
addName(name, listName, *pn);
printf("%s has been added", name);
} else
printf("The student was exist\n");
}


int findName(char name[31], char listName[][31], int n) {
int found = FALSE;
int i, id;
id = -1;
for(i = 0; i < n && (!found); i++)
if(stricmp(listName[i], name) == 0) {
found = TRUE;
id = i;
}

return id;
}

void addName(char str[31], char listName[][31], int* pn) {
if(*pn > 100)
printf("List is full !!");
else
strcpy(listName[(*pn)++],str);
}

提前感谢您的帮助!!

最佳答案

它没有崩溃。现在由您来决定让它按您的意愿工作。

void addStudent(char* name, char listName[][31], int* n) {
int id;
// printf("%s", name);
id = findName(name, listName, n);
if(id < 0) {
addName(name, listName, n);
printf("%s has been added\n", name);
} else
printf("The student already exists\n");
}


int findName(char* name, char listName[][31], int n) {
int found = 0;
int i, id;
id = -1;
for(i = 0; i<100 && &(n) < 100 &&(!found); i++)
if(strcmp(listName[i], name) == 0) {
found = 1;
id = i;
}
return id;
}

void addName(char str[31], char listName[][31], int* pn) {
if(pn > 100)
printf("List is full !!\n");
else
strcpy(listName[(*pn)++],str);
}


void main(int argc, char *argv[]) {
int n = 0;
char listStudent[100][31];
int id;
addStudent("John ABC", listStudent, &(n));
addStudent("David Davinci", listStudent, &(n));
}

关于使用数组 char* 的 C 程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39876302/

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