为struct数组元素分配内存(字符串)

时间:2014-11-02 11:24:11

标签: c arrays string memory struct

我正在尝试从键盘读取并将信息存储在我的结构书中。要求用户输入数组大小,并动态地将大小分配给我的book数组。但是当n> 1,运行时错误是exc_bad_access。当n = 1时,我不知道它为什么会起作用,当n> 1时它不起作用。 1。

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

struct book
{
    char *title;
    char *author;
    double price;
};

int main()
{
    int n, i = 0;
    printf("please enter the value for n\n");
    scanf("%d", &n);

    struct book *stack = malloc(sizeof(struct book) * n);
    stack->author = malloc(sizeof(char) * 100);
    stack->title = malloc(sizeof(char) * 100);
    //allocate memory for book and struct members
    while (i < n )
    {
        printf("Please enter the title\n");
        scanf("%s", stack[i].title);
        printf("Please enter the author\n");
        scanf("%s", stack[i].author);
        printf("Please enter the price\n");
        scanf("%lf", &stack[i].price);
        i ++;
    }
    free(stack);
    return 0;
}

3 个答案:

答案 0 :(得分:2)

您为所输入的任何大小的元素分配了足够的结构,但不是缓冲区的空间

struct book *stack = malloc(sizeof(struct book) * n);
stack->author = malloc(sizeof(char) * 100);
stack->title = malloc(sizeof(char) * 100);
// what about stack[1].author, stack[2].author and the rest??

这将改为:

struct book *stack = malloc(sizeof(struct book) * n);
for (int i = 0; i < n; ++i) {
    stack[i].author = malloc(sizeof(char) * 100);
    stack[i].title = malloc(sizeof(char) * 100);
}

记得要释放你的记忆。

答案 1 :(得分:1)

对于堆栈中的每本书,您必须为作者和标题分配内存。

for(int i = 0; i < n; i++)
{
    stack[i].author = malloc(sizeof(char) * 100);
    stack[i].title = malloc(sizeof(char) * 100);
}

您只为第一个元素分配内存。

答案 2 :(得分:0)

您需要为

分配内存
char *title;
char *author;  

执行struct book *stack = malloc(sizeof(struct book) * n);内存分配给char*指针(4或8个字节,具体取决于您正在构建的平台)。

所以你需要为内部值分配一些内存

while (i < n )
{
    char *title = malloc(255 * sizeof(char));
    printf("Please enter the title\n");
    scanf("%s", title);
    stack[i].title = title;
    .....
    i ++;
}
相关问题