[英]Segfault when populating char* array
我正在嘗試將以'\\ 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;
應該更容易char *tab;
而是分配一個字符數組,就像您的代碼一樣。 您必須將元素訪問權限更改為tab[y * width + x]
而不是tab[y][x]
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.