simon_george_7472
simon_george_7472

Reputation: 13

How to make an array of structs

I am confused as to how to make an array of structs. Here is my code:

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

typedef struct line
{
   int x;
} *line;

int main()
{
    line *array = malloc(10 * sizeof(line));

    int i = 0;

    for(i; i < 2; i++)
    {

        array[i]->x = 5;
    }

    for(i; i < 2; i++)
    {
        printf("%d\n", array[i]->x);
    }

    return 0;
}

My confusion comes from the following: From my understanding if you have a typedef and give it a name to a pointer eg *line then you can access and mutate each item in the struct using the -> symbol. I don't seem to be getting it right and not sure why.

My error:

Segmentation fault (core dumped)

Upvotes: 1

Views: 80

Answers (3)

Jezor
Jezor

Reputation: 3426

Here, fixed it for ya:

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

typedef struct line
{
   int x;
} Line;

int main()
{
    Line* array = malloc(10 * sizeof(line));

    int i = 0;

    for(i; i < 2; i++)
    {

        array[i].x = 5;
    }

    for(i; i < 2; i++)
    {
        printf("%d\n", array[i].x);
    }

    return 0;
}

Upvotes: 1

tijko
tijko

Reputation: 8292

You almost have it, you just need to adjust either your syntax or allocate more memory for each struct:

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

typedef struct line
{
   int x;
} *line;

int main()
{
    line *array = malloc(10 * sizeof(line));

    int i = 0;

    for(i; i < 2; i++)
    {
        // XXX HERE YOU ALLOCATE MORE MEMORY
        array[i] = malloc(sizeof array[i]);
        array[i]->x = 5;
    }
    // XXX RESET "i" TO ZERO
    for(i=0; i < 2; i++)
    {
        printf("%d\n", array[i]->x);
    }

    return 0;
}

You also never reset the i array index variable before using it again.

Upvotes: 0

ShadowRanger
ShadowRanger

Reputation: 155363

You typedef line as a pointer to the struct, not the struct itself. So when you malloc-ed based on the sizeof line, you got space for ten pointers, not ten copies of the struct. Remove the * before line in the typedef, so you get an array of structs, not an array of (unallocated) pointers to struct. You'd then use normal dot access after indexing the pointer.

If you actually want an array of pointers to struct, you'd need to allocate each of the structs individually, which is probably not what you want.

Upvotes: 5

Related Questions