1

I have a structure called table, I just want to create a table, like constructor in java, but when i call this function in main, it gives segmentation fault

struct table *create(char *name,int number,char *s_name) { struct table *newTable; newTable->name = name; newTable->number = number; newTable->s_name = s_name; return newTable; } 

3 Answers 3

11
struct table *newTable = malloc(sizeof(struct table)); 

Don't forget calling free when you're done using it, as C does not have a Garbage Collector like java has.

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

1 Comment

That should be either sizeof (struct table) or sizeof *newTable (I prefer the latter). Unlike C++, struct tags must be preceded by the struct keyword.
9

You haven't allocated any memory for the object, and are de-referencing fields of the structure. You need to use malloc to allocate memory for newTable before accessing it

Comments

1

you are trying to access unallocated/uninitialized memory & SIGSEGV (Segmentation Fault) is perfectly alright for the code unless you allocate memory explicitly using malloc or other memory allocation methods.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.