Memory Allocation for Pointer Array

I need to allocate memory for a pointer that should be used as a 2d array. I know how to allocate memory for char pointers and int pointers. I am confused by how memory is allocated from an array of pointers. presenting the reason would be very helpful, is the code below fine?

char *names[5];
for(i=0;i<5;i++)
{
 names[i]=(*char)malloc(sizeof(char));
}
+3
source share
4 answers

No, this is not because you are allocating an array that assumes measuring only one element of the primitive type char (which is 1 byte).

I assume that you want to highlight 5 pointers to lines inside names, but just pointers.

You must select it according to the size of the pointer times the number of elements:

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

. , , , **

+10

, , 5 . , :

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

, ,

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

, , .

+1

, ,

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

0

, : , , **.

char *names[5];

, , Ak1to, :

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

.

0
source

Source: https://habr.com/ru/post/1771176/


All Articles