<分区>
我有一个字符串数组 (char **
),它被初始化为 NULL
。在我尝试访问它的元素时传递它的地址后,它给出了段错误。
//following code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void parse(char ***test, char *str)
{
int i;
*test = (char**)malloc(sizeof(char*) * 3);
for(i=0; i<3; i++)
{
*test[i] = (char*) malloc(sizeof(char)*(strlen(str)+1));
strcpy(*test[i], str);
}
}
int main(void)
{
int i;
char *str = "Hello world";
char **test = NULL;
parse(&test, str);
for(i=0; i<3; i++)
printf("%s\n", test[i]);
return 0;
}
在函数内部使用调试器解析时,所有元素都有正确的值并正确初始化和分配,但从主函数只有 0 索引行给出正确的值,其余是段错误。