簡體   English   中英

C 程序打印錯誤 output

[英]C program printing wrong output

我正在嘗試創建一個打印整數矩陣的程序,但是 output 在實際矩陣之前返回奇怪的數字。 沒有編譯錯誤。

這是我的代碼的樣子: //ignore void function 現在,專注於主要 function::

#include <stdio.h>
#include <stdlib.h>
//array[30][30] = 2D array of max 30 rows and 30 columns
//n = number of rows and columns
void printmatrix(int array[30][30], int n){
    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
            printf("%d", array[i][j]);
        }

        printf("\n");
    }

    return;
}

int main(){
    int n;
    scanf("%d", &n);

    int ints2D[n][n];

    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
            scanf("%d", &ints2D[i][j]);
        } 
    }

    printmatrix(ints2D, n);

    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
            printf("%d ", ints2D[i][j]);
        }

        printf("\n");
    }

    return 0;
}

這是我的 output (我只想要最后三行)

123
-514159984327663
-51415932632766-514159305
1 2 3 
4 5 6 
7 8 9 

您在printmatrix"%d"中缺少一個空格,更重要的是,除非n為 30,否則為int [30][30]參數傳遞一個int [n][n]數組是不合適的。

void printmatrix(int array[30][30], int n)更改為void printmatrix(int n, int array[n][n]) ,並更改printmatrix(ints2D, n); printmatrix(n, ints2D); . 這使得您傳遞的參數的類型與參數的類型相匹配。

在您的 function 參數中,您將數組定義為固定大小([30][30]),但您傳遞了一個 VLA(在您的示例中為 [3][3]),這使其找到未初始化的 memory 以及為什么您會看到奇怪的數字.

@Eric Postpischil 的回答很到位。 另一種解決方法:2d arrays 可以展平為 1d。 這是適合您的工作代碼:

#include <stdio.h>
#include <stdlib.h>
//array[30][30] = 2D array of max 30 rows and 30 columns
//n = number of rows and columns
void printmatrix(int *array, int n){
    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
            printf("%d ", array[i * n + j]);
        }
    printf("\n");
    }
return;
}

int main(){
    int n;
    scanf("%d", &n);
    int ints2D[n * n];
    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
            scanf("%d", &ints2D[i * n + j]);
        }
    }
    printmatrix(ints2D, n);
    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
            printf("%d ", ints2D[i * n + j]);
        }
        printf("\n");
    }
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM