Dinesh
Dinesh

Reputation: 16436

How can i dynamically allocate memory for a array of pointers in C?

I need to allocate memory dynamically for an array of pointers.

Let us assume,

char *names[50];
char *element;

I used the following code to allocate memory dynamically which is producing error.

names=malloc(sizeof(char *));

Afterwards, i need to assign another character pointer to this one, say

names=element;

I am getting error as ": warning: assignment from incompatible pointer type".

How can i resolve this?

Upvotes: 0

Views: 3394

Answers (3)

IsKernel
IsKernel

Reputation: 158

You may want to check this tutorial out: http://dystopiancode.blogspot.com/2011/10/dynamic-multidimensional-arrays-in-c.html It says how to allocate dynamic memory for arrays,matrices,cubes and hypercube and also how you can free it.

Upvotes: 1

caf
caf

Reputation: 239321

If you want to dynamically allocate an array of N char *pointers, then you would use:

char **names;

names = malloc(N * sizeof p[0]);

To assign the char * value element to the first element in the array, you would then use:

names[0] = element;

Upvotes: 1

shenles
shenles

Reputation: 582

names=malloc(sizeof(char *));

Will allocate either 4 or 8 bytes (depending on your system). This doesn't make sense since your array was already sized at 50 entries in the declaration...

names=element;

This is not how arrays are used in C. You have declared that there are 50 elements in "names" and each one is allocated as a different pointer to an array of characters. You need to decide which element in the array you want to assign. For eaxample:

char *test1 = "test string 1";
char *test2 = "test string 2";

names[0] = test1; // Assign pointer to string 1 to first element of array
names[1] = test2; // Assign pointer to string 2 to second element of array

Upvotes: 2

Related Questions