【发布时间】:2020-04-14 20:12:54
【问题描述】:
任务是为结构数组动态分配内存,然后从键盘填充它们。我能够为数组中的每个结构实例动态分配和填充页面数量,但是当我尝试通过执行以下操作将 char* 添加到其中时:
strcpy(myArray[i]->author, authorName);
但是每次我得到分段错误,那我做错了什么? 有没有可能这个问题实际上出在内存分配上?
这里是代码
#include <stdlib.h>
#include <string.h>
struct Book {
char* author;
char* title;
int pages;
int pubYear;
int copies;
};
void allocList(struct Book **myArray, int booksAmount);
void fillKeyboard(struct Book **myArray, int booksAmount);
int main(void) {
struct Book *booksList = NULL;
int booksAmount = 3;
allocList(&booksList, booksAmount);
fillKeyboard(&booksList, booksAmount);
return 0;
}
void allocList(struct Book **myArray, int booksAmount) {
*myArray = (struct Book*) malloc(sizeof(struct Book) * 100);
printf("memory for %d books was allocated \n", booksAmount);
}
void fillKeyboard(struct Book **myArray, int booksAmount) {
int i = 0;
char* authorName = "author name";
while (booksAmount--) {
printf("book number %d \n", i + 1);
printf("enter amount of pages: ");
scanf("%d", &(*myArray)[i].pages);
printf("\nenter author: ");
strcpy(myArray[i]->author, authorName);
printf("%s is \n", authorName);
i++;
printf("\n");
}
}
谢谢。
【问题讨论】:
-
c和c++是具有不同概念的不同语言,答案会有所不同。因此,请删除其中一个标签以明确您使用哪种语言。根据您提出的关于c而不是c++的问题的代码 -
strcpy(myArray[i]->author, authorName);最有可能是这里的罪魁祸首。 -
请注意,代码永远不会要求新的
authorName。 -
你必须为
author分配内存调用之前strcpy。即:(*myArray)[i].author = malloc(MAX_AUTHOR_NAME_LENGTH+1);。您的strcpy调用的参数也不正确。它必须是strcpy((*myArray)[i].author, authorName);。您在函数fillKeyboard中对参数myArray的额外间接使代码不必要地复杂化。
标签: c struct dynamic-memory-allocation