Search code examples
cstringmultidimensional-arraystring-concatenationstrcat

Concatenating 2D array into string causing segmentation fault


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!


Solution

  • The argument is of type int (*)[5] and the parameter is of type int**, these are not compatible, use:

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

    Furthermore, strcat's second parameter is expecting a char array and you are passing single char arguments to it, aside from the fact that str points to a string literal which is constant and cannot be altered.

    You wouldn't need to use strcat to do this, you can assign these directly to output with a proper conversion:

    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);
    }
    

    This will work only for single digits, wich, I gather, is the intended purpose given the size of the output string and the rest of the code.