【问题标题】:Concatenating 2D array into string causing segmentation fault将二维数组连接成字符串导致分段错误
【发布时间】:2020-08-01 07:04:30
【问题描述】:

我正在尝试使用strcat 将一个矩阵连接成一个长字符串,但每当我尝试访问矩阵或使用strcat 时,都会出现段错误。我一进入函数就会出现分段错误。第一个 printf 永远不会执行。

void concatMatrix(int **matrix, char *output){ 
  printf("%s", "SDFSDFDSFDSFDSF");

  char *str = "";
  char *temp = "sdds";
  for(int i = 0; i < 5; i++) {
    for (int j = 0; j < 5; j++) {
       // temp = (char)matrix[i][j];
       // strcat(str, temp);
       // strcat(str, ' ');
       // printf("%d\n", matrix[i][j]);
    }
    // strcat(str, "\n");
    strcat(output, str);
    // printf("%s", output);
  }
}

这就是矩阵和输出的声明方式,并且在调用函数之前,矩阵被填充了值。

int matrix[5][5];
char output[25];

每当我尝试使用矩阵或输出或strcpy() 时,我都会遇到分段错误。我可以简单地在 str 或 temp 上使用printf,但仅此而已。所有注释掉的行都会导致段错误。任何帮助将不胜感激!

【问题讨论】:

  • 当你将这样声明的变量:int matrix[5][5]; 传递给一个函数时,它会衰减为一个 single 指针(int*not 一个int**。它将指向程序“感知”为 25 个整数的一维数组的数据块的开头。
  • 引用你的注释掉的// strcat(str, temp); 你不能用字符串文字做到这一点。除了*str指向一个1字节的空间外,它是只读的。
  • 请张贴Minimal Reproducible Example,这是显示问题的最短完整代码。
  • 请在printf调试提示之后添加fflush(stdout),以确保它被打印出来。当程序崩溃时,缓冲的输出通常会被丢弃。回到我之前的评论,你可以尝试char str[1024] = "";,或者更长的时间,并使用strncat防止溢出。
  • 感谢这有很大帮助!将我的字符串更改为非只读修复了很多问题。

标签: c string multidimensional-array string-concatenation strcat


【解决方案1】:

参数类型为int (*)[5],参数类型为int**,这些不兼容,使用:

void concatMatrix(int matrix[][5], char *output);

此外,strcat 的第二个参数需要一个 char 数组,而您正在向它传递单个 char 参数,除了 str 指向一个常量且无法更改的字符串文字。

您不需要使用strcat 来执行此操作,您可以通过适当的转换直接将它们分配给output

Running sample

#include <stdio.h>

void concatMatrix(int matrix[][5], char *output)
{  
    int index = 0;
    for (int i = 0; i < 5; i++)
    {
        for (int j = 0; j < 5; j++, index++)
        {        
        output[index] =  matrix[i][j] + '0'; //convert from int to char and assign to output
        }       
    }
    output[index] = '\0'; //null terminate the string
}

int main()
{
    int matrix[5][5] = {{1, 4, 3, 5, 2},
                        {7, 9, 5, 9, 0},
                        {1, 4, 3, 5, 2},
                        {1, 4, 3, 5, 2},
                        {7, 9, 5, 9, 0}};
    char output[26]; //must have space for null terminator
    concatMatrix(matrix, output);
    printf("%s", output);
}

这仅适用于单个数字,我认为这是考虑到output 字符串和其余代码的大小的预期目的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-28
    • 2012-02-25
    • 2023-04-02
    • 2015-06-23
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    • 2017-02-25
    相关资源
    最近更新 更多