【发布时间】:2018-01-28 10:41:20
【问题描述】:
我正在尝试将由 '\n' 分隔的字符串拆分为字符串数组。该字符串表示一个 NxN 矩形,因此矩阵上的每一行都将包含相同数量的字符。这是我尝试过的:
char **string_to_tab(char *str, int width, int height)
{
int i; //counter to scan str
int x; //counter for tab column no.
int y; //counter for tab row no.
char **tab;
i = 0; //I initialise variables
x = 0; //separately because I
y = 0; //like to :P
tab = (char**)malloc(sizeof(char) * height * width);
while (y < height)
{
while (x < width)
{
if (str[i] != '\n' || !(str[i]))
{
tab[y][x] = str[i]; //assign char to char* array
x++;
}
i++;
}
x = 0;
y++;
}
return (tab);
}
这给我一个分段错误,调用它看起来像这样:
char *str = "+--+\n| |\n| |\n+--+";
char **matrix = string_to_tab(str, 4, 4);
【问题讨论】:
-
(char**)malloc(sizeof(char) * height * width);不,malloc不能那样工作。 -
请不要编辑问题代码以使现有或待处理的 cmets/answers 无效。对于那些自愿努力的人来说,这很烦人。
-
这里有很多可能性:stackoverflow.com/q/917783/694576
标签: c matrix segmentation-fault