angerhang
angerhang

Reputation: 327

Allocate memory for struct array element (string)

I am trying to read from keyboard and store the info in my struct book. The user is asked to enter the array size and I dynamically allocate the size to my book array. But when n > 1, the run time error is exc_bad_access. I don't know why it works when n = 1 and it doesn't work when n > 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;
}

Upvotes: 1

Views: 1731

Answers (3)

Marco A.
Marco A.

Reputation: 43662

You're allocating enough structures for any size of elements you input, but not the space for the buffers:

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??

This will work instead:

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);
}

And remember to free your memory as well.

Upvotes: 3

l0gg3r
l0gg3r

Reputation: 8954

You need to allocate memory for

char *title;
char *author;  

When you do struct book *stack = malloc(sizeof(struct book) * n); memory is allocated for char* pointers (4 or 8 bytes depending on platform you're building).

So you need to allocate some memory for inside values

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

Upvotes: 0

Vincent
Vincent

Reputation: 646

For each book in the stack, you have to allocate memory for the author and the title.

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

You are only allocating memory for the first element.

Upvotes: 2

Related Questions