簡體   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