1
#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!!!

2
  • You malloc space for size pointers (the joys of typedefs) And the pointers are uninitialised; they point to nothing (or they point to anything, if you like) Commented Mar 28, 2016 at 13:17
  • 1
    1) Don't typedef pointers. 2) Don't cast the result of malloc & friends or void * in general in C. Commented Mar 28, 2016 at 14:04

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.