use*_*534 19 c arrays dynamic-memory-allocation pointer-to-pointer
我正在尝试编写一个程序,该程序从文本文件中读取一系列字符串,并将它们存储在字符串数组中,为每个元素动态分配内存.我的计划是使用指针将每个字符串存储在一个数组中,然后在读入更多数据时增大数组大小.我无法理解为什么我的测试代码无效.这是一个可行的想法吗?
char *aPtr;
aPtr =(char*)malloc(sizeof(char));
aPtr[0]="This is a test";
printf("%s",aPtr[0]);
Run Code Online (Sandbox Code Playgroud)
das*_*ght 19
在C中,字符串是a char*.类型的动态数组T表示为指向T,因此对于char*那将是char**不仅仅是char*您声明它的方式.
毫无疑问,编译器已发出一些警告.注意这些警告,通常它们可以帮助您了解要做什么.
以下是开始测试的方法:
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.
Run Code Online (Sandbox Code Playgroud)
char *str; //single pointer
Run Code Online (Sandbox Code Playgroud)
有了这个,你可以存储一个字符串.
存储array of strings你的需要two dimensional character array
否则array of character pointers要不然double pointer
char str[10][50]; //two dimensional character array
Run Code Online (Sandbox Code Playgroud)
如果你这样声明你不需要分配内存,因为这是静态声明
char *str[10]; //array of pointers
Run Code Online (Sandbox Code Playgroud)
在这里,您需要为每个指针分配内存
循环遍历数组以为每个指针分配内存
for(i=0;i<10;i++)
str[i]=malloc(SIZE);
Run Code Online (Sandbox Code Playgroud)
char **str; //double pointer
Run Code Online (Sandbox Code Playgroud)
在这里,您需要为指针数分配内存,然后为每个指针分配内存.
str=malloc( sizeof(char *)*10);
Run Code Online (Sandbox Code Playgroud)
然后循环遍历数组为每个指针分配内存
for(i=0;i<10;i++)
str[i]=malloc(SIZE);
Run Code Online (Sandbox Code Playgroud)
char * aPtr;
Run Code Online (Sandbox Code Playgroud)
是指向一个字符的指针,你为此分配了内存 1字符.
干
aPrt[0] = "test";
Run Code Online (Sandbox Code Playgroud)
您解决这个记忆一个字符,然后存储字面的地址"test"到它.这将失败,因为这个地址最有可能比一个角色更宽.
修复代码的方法是为指向字符的指针分配内存.
char ** aPtr = malloc(sizeof(char *));
aPtr[0] = "test";
printf("%s", aPtr[0]);
Run Code Online (Sandbox Code Playgroud)
更优雅,更强大的方法是通过执行以下操作来分配相同的(以及添加强制性错误检查):
char ** aPtr = malloc(sizeof *aPtr);
if (NULL == aPtr)
{
perror("malloc() failed");
exit(EXIT_FAILURE);
}
...
Run Code Online (Sandbox Code Playgroud)