Rio
Rio

Reputation: 51

Malloc struct pointer error

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

typedef struct vertex_t* Vertex;
struct vertex_t {
    int id;
    char *str;
};

int main(int argc, char* argv[])
{
    int size = 10;
    Vertex* vertexList = (Vertex*)malloc(size * sizeof(Vertex));
    vertexList[0]->id = 5;
    vertexList[0]->str = "helloworld";
    printf("id is %d", vertexList[0]->id);
    printf("str is %s", vertexList[0]->str);

    return(0);
}

Hi! I'm trying to malloc for an array of Vertex. When i run the program, it didn't print out anything and says that the program has stopped running. But if i just gave a value to vertexList[0]->id and not vertexList[0]->str and printed just vertexList[0], it would print out "id is 5"...and then still program stopped. So i think i did something wrong with the malloc part?? :/ Thank you in advance for the help!!!

Upvotes: 1

Views: 491

Answers (1)

rodrigo
rodrigo

Reputation: 98526

Doing a typedef of a pointer type is usually a bad idea, because you don't know what is a pointer and what not, and you end up messing the memory management.

Ignore the Vertex typedef and just do:

struct vertex_t* vertexList = malloc(size * sizeof(struct vertex_t));

And everything else will fit together.

If you think that the struct vertex_t is very verbose, you may do:

typedef struct vertex_t Vertex;
Vertex *vertexList = malloc(size * sizeof(Vertex));

Note how my typedef does not hide a pointer, only a struct.

Upvotes: 5

Related Questions