为指针数组动态内存分配 [英] Dynamic memory allocation for pointer arrays

查看:295
本文介绍了为指针数组动态内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个程序,读取一系列从一个文本文件字符串和字符串数组存储这些,每个元素动态分配内存。我的计划是使用指针存储阵列中的每个字符串,然后成长数组的大小为更多的人在读。我无法理解,为什么我的测试code以下无法正常工作。这是一个可行的主意?

 的char * APTR;
APTR =(字符*)malloc的(的sizeof(字符));APTR [0] =这是一个测试;
的printf(%S,APTR [0]);


解决方案

在C语言中的字符串是一个的char * 。键入 T 的动态数组重新psented为指针$ P $到 T ,所以的char * 这将是的char ** ,不是一个简单的的char * 的这样你宣布它。

编译器,毫无疑问,发表了关于它的一些警告。注意这些警告,很多时候他们帮助你明白该怎么做。

下面是如何开始你的测试:

 的char ** APTR;
INT LEN = 1; // 1串启动
APTR =的malloc(sizeof的(字符*)* LEN); //不要用C的malloc投
APTR [0] =这是一个测试;
的printf(%S,APTR [0]); //这应该现在的工作。

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]);

解决方案

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

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.

这篇关于为指针数组动态内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆