分段错误:指向字符串数组的指针
Segmentation fault: Pointer to an array of string
我有一个字符串数组 (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 个索引行给出了正确的值,其余为段错误。
*test[0]
应该是 (*test)[i]
.
http://en.cppreference.com/w/c/language/operator_precedence说[]
比*
优先级高,这不是你想要的
您也不应覆盖索引 0。
sizeof(char)
始终为 1,因此您可以将其保留。您也不应投射 malloc
的 return 值并测试是否成功。
这里的问题是
*test[0] = (char*) malloc(sizeof(char)*(strlen(str)+1));
您总是将内存分配给索引 0
。
此外,在 operator precedence table 之后,您需要先取消引用 test
,然后对其应用索引,因此,您基本上需要像
一样重新编写代码
(*test)[0] = malloc( strlen(str) + 1);
请注意:
See why not to castmalloc()
和家人的return值C
.
sizeof(char)
保证产出1
。乘以它是多余的。
我有一个字符串数组 (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 个索引行给出了正确的值,其余为段错误。
*test[0]
应该是 (*test)[i]
.
http://en.cppreference.com/w/c/language/operator_precedence说[]
比*
优先级高,这不是你想要的
您也不应覆盖索引 0。
sizeof(char)
始终为 1,因此您可以将其保留。您也不应投射 malloc
的 return 值并测试是否成功。
这里的问题是
*test[0] = (char*) malloc(sizeof(char)*(strlen(str)+1));
您总是将内存分配给索引 0
。
此外,在 operator precedence table 之后,您需要先取消引用 test
,然后对其应用索引,因此,您基本上需要像
(*test)[0] = malloc( strlen(str) + 1);
请注意:
See why not to cast
malloc()
和家人的return值C
.sizeof(char)
保证产出1
。乘以它是多余的。