简体   繁体   中英

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?

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

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;

您可能需要查看本教程: http : //dystopiancode.blogspot.com/2011/10/dynamic-multiDimension-arrays-in-c.html它说明了如何为数组,矩阵,多维数据集和超立方体分配动态内存,以及还有如何释放它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM