I'm trying to concatenate a matrix into one long string using strcat, but keep getting seg faults whenever I attempt to access the matrix or use strcat. The segmentation fault occurs as soon as I enter the function. The first printf never executes.
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);
}
}
This is how matrix and output were declared, and matrix was filled with values before calling the function.
int matrix[5][5];
char output[25];
Whenever I try to use matrix or output or strcpy() I get a segmentation fault. I can use printf simply on str or temp, but that is all. All the lines commented out will cause a seg fault. Any help would be greatly appreciated!
int matrix[5][5];to a function, it decays to a single pointer (int*) not anint**. It will point to the start of the block of data that is 'perceived' by the program as a 1D array of 25 integers.// strcat(str, temp);you can't do that with a string literal. Apart from*strpointing to a 1-byte space, it is read-only.fflush(stdout)after theprintfdebugging cue, to be sure it is printed. When a program crashes, buffred output is usually discarded. Back to my earlier comment, you can trychar str[1024] = "";instead, or longer, and guarded from overflow by usingstrncat.