简体   繁体   English

填充char *数组时出现段错误

[英]Segfault when populating char* array

I am trying to split a string delimited by '\\n' into an array of strings. 我正在尝试将以'\\ n'分隔的字符串拆分为字符串数组。 The string represents an NxN rectangle so each row on the matrix will contain the same number of characters. 该字符串表示一个NxN矩形,因此矩阵上的每一行将包含相同数量的字符。 This is what I have tried: 这是我尝试过的:

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);
}

This gets me a segmentation fault, calling it would look something like this: 这给我带来了分段错误,调用它看起来像这样:

char *str = "+--+\n|  |\n|  |\n+--+";
char **matrix = string_to_tab(str, 4, 4);

Your variable tab is a pointer to a pointer, but you reserve a single array of characters with malloc . 您的变量tab是指向指针的指针,但是您使用malloc保留了单个字符数组。 If you want to use tab as an array of pointers as in your code, you have to allocate an array of char pointers first, and then allocate an array of char for each row. 如果要像代码中那样使用tab作为指针数组,则必须先分配一个char指针数组,然后再为每行分配一个char数组。 But this is complicate. 但这很复杂。

It should be easier to use char *tab; 使用char *tab;应该更容易char *tab; instead, and allocate just an an array of characters as your code does already. 而是分配一个字符数组,就像您的代码一样。 You have to change the element access to tab[y * width + x] instead of tab[y][x] . 您必须将元素访问权限更改为tab[y * width + x]而不是tab[y][x]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM