diesel diesel - 1 year ago 74
C Question

What is the way of correct way in using calloc for an array?

I want to create a pointer to an array of pointers (with 10 pointers in the array), then I want to give a pointer a value.

This is what I have so far:

char **arraypointer = calloc (10, sizeof (char*));

How will I give value to this array?

I've tried:

arraypointer[0] = "string"

But I get a seg fault.


I want to create a pointer that points to an array of pointers. Each of these pointers will have a struct property. How is it possible to access the struct property for this pointer? I have no code to post because I am still trying to figure out how it should look. The struct for this pointer will contain a string which is a char *string and an int number. I am thinking of it working like this:

arraypointer[0]->string = "this";
arraypointer[0]->number = 3;

Answer Source


struct mystruct* pointer = calloc(N, sizeof(struct mystruct));
pointer[0].string = "this"; //notice . instead of ->
pointer[0].number = 3;

Original answer:

char **arraypointer = calloc (10, sizeof (char*));
arraypointer[0] = "string";

These two lines are perfectly fine. You'd get a segfault(Undefined behavior, actually) if you tried to do something like

arraypointer[0][3] = 's';


Also, you'd get in trouble if you did

strcpy(arraypointer[0], "string");

because you haven't actually allocated any memory that arraypointer[i] point to

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download