5

I need to allocate memory for a pointer which needs to be used as a 2d array.I know how to allocate memory for char pointers and int pointers I am confused how memory is allocated of a array of pointers.A pictorial representation of the reason would be very helpful,also is the code below fine?

char *names[5];
for(i=0;i<5;i++)
{
 names[i]=(*char)malloc(sizeof(char));
}
asked Oct 24, 2010 at 15:44
2
  • 1
    It's not clear what your question is. Your code already does something valid; each element of names[] points at a char allocated on the heap. What do you actually need to do? Commented Oct 24, 2010 at 15:47
  • 1
    Once you have it correct, see this question about how to free the memory: stackoverflow.com/questions/1733881/… Commented Oct 24, 2010 at 15:49

4 Answers 4

14

No, this is not because you are allocating the array assuming a dimension of just 1 element of primitive type char (which is 1 byte).

I'm assuming you want to allocate 5 pointers to strings inside names, but just pointers.

You should allocate it according to the size of the pointer multiplied by the number of elements:

char **names = malloc(sizeof(char*)*5);

You don't need to allocate them one by one with a loop. Note that you need to specify that it is a pointer-of-pointers by using **

answered Oct 24, 2010 at 15:46
Sign up to request clarification or add additional context in comments.

1 Comment

Don't cast the return value from malloc(). c-faq.com/malloc/mallocnocast.html
3

What you're doing is allocating space for 5 chars. You could write this and it'll have the same result:

char *names = (char *)malloc(sizeof(char) * 5);

If you want to have an array of pointers, I think this'd be the best code

char **names = (char **)malloc(sizeof(char *) * 5);

I'm not a super-coder, but as what I now, this is the right solution.

answered Oct 24, 2010 at 15:49

Comments

0

Also, in short you can do the following too in this case for allocating storage for five characters

names = (char*)malloc(5 * sizeof(char))

answered Oct 24, 2010 at 15:47

Comments

0

Emphisizing what Jack said in in the end: his code works only if the array is declared as a pointer-of-pointers by using **.

When the array is declared as

char *names[5];

I guess the right way of allocating memory is almost as Ak1to did, but multiplying by the wanted size of the string of chars:

char *names[5];
for(i=0;i<5;i++)
{
 names[i]=(char *)malloc(sizeof(char)*80);
}

else the compiler throws an error about incompatible types.

answered Jul 19, 2013 at 20:16

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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