c-将2D阵列连接成字符串,导致分段错误



我试图使用strcat将矩阵连接成一个长字符串,但每当我尝试访问矩阵或使用strcat时,都会出现seg错误。我一进入函数,分段故障就出现了。第一个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("%dn", matrix[i][j]);
}
// strcat(str, "n");
strcat(output, str);
// printf("%s", output);
}
}

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

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

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

参数类型为int (*)[5],参数类型为int**,它们不兼容,请使用:

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

此外,strcat的第二个参数需要一个char数组,而您正在向它传递单个char参数,除了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] = ''; //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字符串的大小和代码的其余部分,这是预期的目的。

最新更新