我如何将char *插入结构数组?

问题描述 投票:0回答:2

任务是为结构数组动态分配内存,然后从键盘填充它们。我能够为数组中的每个struct实例动态分配和填充页面数量,但是当我尝试通过执行类似以下操作向其中添加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 struct dynamic-memory-allocation
2个回答
2
投票
myArray[i].author=malloc(sizeof(char) * 100);

您的while循环应如下所示:

 while (booksAmount--) {
    myArray[i].author=malloc(sizeof(char) * 100);
    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");
}

请记住,100是一个“魔术数字”,因此,如果作者姓名超过100个字符,那么它将不起作用

编辑:与标题相同,您需要在数组的元素中分配所需的内存

0
投票
struct Book { char* author; char* title; int pages; int pubYear; int copies; struct Book *next; };

程序当然会复杂一些,但是结果是干净的内存使用和真正的动态程序。

© www.soinside.com 2019 - 2024. All rights reserved.