C语言 指针数组的动态内存分配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19068643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:34:30  来源:igfitidea点击:

Dynamic memory allocation for pointer arrays

carraysdynamic-memory-allocationpointer-to-pointer

提问by user2826534

I'm am trying to write a program that reads in a series of strings from a text file and stores these in an array of strings, dynamically allocating memory for each element. My plan was to store each string in an array using a pointer and then grow the array size as more were read in. I am having trouble to understand why my test code below is not working. Is this a workable idea?

我正在尝试编写一个程序,该程序从文本文件中读取一系列字符串并将它们存储在字符串数组中,为每个元素动态分配内存。我的计划是使用指针将每个字符串存储在一个数组中,然后随着读入的内容增加数组大小。我无法理解为什么下面的测试代码不起作用。这是一个可行的想法吗?

char *aPtr;
aPtr =(char*)malloc(sizeof(char));

aPtr[0]="This is a test";


printf("%s",aPtr[0]);

回答by dasblinkenlight

In C a string is a char*. A dynamic array of type Tis represented as a pointer to T, so for char*that would be char**, not simply a char*the way you declared it.

在 C 中,字符串是一个char*. 类型的动态数组T表示为指向 的指针T,因此对于char*该类型而言,将是char**,而不仅仅是char*您声明它的方式。

The compiler, no doubt, has issued some warnings about it. Pay attention to these warnings, very often they help you understand what to do.

毫无疑问,编译器已经发出了一些警告。请注意这些警告,它们通常会帮助您了解该怎么做。

Here is how you can start your testing:

您可以通过以下方式开始测试:

char **aPtr;
int len = 1; // Start with 1 string
aPtr = malloc(sizeof(char*) * len); // Do not cast malloc in C
aPtr[0] = "This is a test";
printf("%s",aPtr[0]); // This should work now.

回答by Gangadhar

char *str; //single pointer   

With this you can store one string.

有了这个,您可以存储一个字符串。



To store array of stringsyou Need two dimensional character array

存储array of strings你需要two dimensional character array

or else array of character pointersor else double pointer

否则array of character pointers否则double pointer



char str[10][50]; //two dimensional character array

If you declare like this you need not allocate memory as this is static declaration

如果你这样声明,你不需要分配内存,因为这是静态声明



char *str[10];  //array of pointers 

Here you need to allocate memory for each pointer

这里需要为每个指针分配内存

loop through array to allocate memory for each pointer

循环遍历数组为每个指针分配内存

for(i=0;i<10;i++) 
str[i]=malloc(SIZE);


char **str;    //double pointer

Here you need to allocate memory for Number of pointers and then allocate memory for each pointer .

这里需要为 Number of pointers 分配内存,然后为每个指针分配内存。

str=malloc( sizeof(char *)*10);

And then loop through array allocate memory for each pointer

然后循环遍历数组为每个指针分配内存

for(i=0;i<10;i++) 
str[i]=malloc(SIZE);

回答by alk

char * aPtr;

is as pointer to a character, to which you allocated memory to hold exactly 1character.

作为指向字符的指针,您分配了内存以准确保存1字符。

Doing

正在做

aPrt[0] = "test";

you address the memory for this onecharacters and try to store the address of the literal "test"to it. This will fail as this address most likley is wider then a character.

您解决这个记忆一个字符,然后字面的地址保存"test"到它。这将失败,因为这个地址最有可能比一个字符更宽。

A fix to your code would be to allocate memory for a pointer to a character.

修复您的代码是为指向字符的指针分配内存。

char ** aPtr = malloc(sizeof(char *));
aPtr[0] = "test";
printf("%s", aPtr[0]);

Are more elegant and more over robust approach would be to allocate the same (as well as adding the mandatory error checking) by doing:

更优雅和更健壮的方法是通过执行以下操作来分配相同的(以及添加强制性错误检查):

char ** aPtr = malloc(sizeof *aPtr);
if (NULL == aPtr)
{
  perror("malloc() failed");
  exit(EXIT_FAILURE);
}

...

回答by Tonmoy

You are doing it totally wrong. The correct version of your code should be like this:

你这样做是完全错误的。您的代码的正确版本应该是这样的:

int main ()
{
char *aPtr;
aPtr =(char*)malloc(20*sizeof(char));
aPtr ="This is a test";
printf("%s",aPtr);
}

You can use pointer array. if you want to store multiple string. Yes I know using for loop will be easy. But I am trying to explain in simple way even a beginner can understand.

您可以使用指针数组。如果要存储多个字符串。是的,我知道使用 for 循环很容易。但我试图以简单的方式进行解释,即使是初学者也能理解。

int main ()
{
char *aPtr[10];
aPtr[0] =(char*)malloc(20*sizeof(char));
aPtr[0] ="This is a test";
aPtr[1] =(char*)malloc(20*sizeof(char));
aPtr[1] ="This is a test2";
printf("%s\n%s\n",aPtr[0],aPtr[1]);
 }