0

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?

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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;

1 Comment

Correct. To clarify: your code to dynamically allocate "*names[50]" like "char **names = malloc (sizeof (char) * 50);". At this point, you would have space for 50 pointers ... and then you would ALSO need to allocate space for the 50 strings (separately!).
1

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.

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.