简体   繁体   中英

Segfault when populating char* array

I am trying to split a string delimited by '\\n' into an array of strings. The string represents an NxN rectangle so each row on the matrix will contain the same number of characters. 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 . 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. But this is complicate.

It should be easier to use 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] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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