繁体   English   中英

将二维数组连接成字符串导致分段错误

[英]Concatenating 2D array into string causing segmentation fault

我正在尝试使用strcat将矩阵连接成一个长字符串,但每当我尝试访问矩阵或使用strcat时,都会出现段错误。 一进入function就会出现分段错误。 第一个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);
  }
}

这就是矩阵和 output 的声明方式,矩阵在调用 function 之前填充了值。

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

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

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

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

此外, strcat的第二个参数需要一个 char 数组,并且您将单个 char arguments 传递给它,除了str指向一个常量且无法更改的字符串文字这一事实。

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

运行示例

#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字符串的大小和代码的 rest 的大小,这仅适用于单个数字。

暂无
暂无

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

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