我正在尝试将一个由 '\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);
最佳答案
您的变量 tab
是指向指针的指针,但您使用 malloc
保留了一个字符数组。如果你想在你的代码中使用tab
作为一个指针数组,你必须先分配一个char
指针数组,然后再分配一个数组char
每行。但这很复杂。
使用 char *tab;
应该更容易,并且只分配一个字符数组,就像您的代码已经做的那样。您必须将元素访问更改为 tab[y * width + x]
而不是 tab[y][x]
。
关于c - 填充 char* 数组时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48485429/