你能告诉我我做错了什么吗?打印 printf("%s\n",text[0]);
我创建了 char **text;
并 malloc
了所有指针。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char **text;
int main()
{
int i;
text = malloc(20000);
for(i=0; i < 20000; i++) {
text[i] = malloc(4);
memcpy(text[i], "test",4);
}
printf("%s\n",text[0]);
printf("%s\n",text[1]);
}
最佳答案
我相信您正在寻找这样的东西:
int numElements = 20000, i;
// Allocate an array of char pointers
text = malloc(numElements * sizeof( char *));
for( i = 0; i < numElements; i++) {
// 4 for the length of the string "test", plus one additional for \0 (NULL byte)
text[i] = malloc( (4 + 1) * sizeof( char));
memcpy( text[i], "test\0", 5);
}
这是一个 online demo显示它正在工作,因为它会产生输出:
test
test
关于c - c中带有malloc的字符串数组的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16390117/