将二维数组连接成导致分段错误的字符串
Concatenating 2D array into string causing segmentation fault
我正在尝试使用 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 (*)[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] = '[=11=]'; //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
字符串和其余代码的大小的预期目的。
我正在尝试使用 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 (*)[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] = '[=11=]'; //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
字符串和其余代码的大小的预期目的。