【问题标题】:Segfault when populating char* array填充 char* 数组时出现段错误
【发布时间】: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


【解决方案1】:

您的变量tab 是一个指向指针的指针,但您使用malloc 保留了一个字符数组。如果你想在你的代码中使用tab作为一个指针数组,你必须首先分配一个char指针数组,然后为每一行分配一个char数组。但这很复杂。

改用char *tab; 应该更容易,并且像您的代码一样只分配一个字符数组。您必须将元素访问权限更改为 tab[y * width + x] 而不是 tab[y][x]

【讨论】:

  • 谢谢,您的回复对我帮助很大。我现在更好地理解了如何将内存分配给 n 维数组。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-16
  • 2014-01-05
  • 1970-01-01
  • 2011-05-20
  • 1970-01-01
  • 2013-04-08
相关资源
最近更新 更多