簡體   English   中英

C:傳遞2D int數組

[英]C: Pass 2D int array

我有問題將2d整數數組傳遞給C中的函數數組。我的任務是從stdin掃描整數行到2d數組,然后將該數組傳遞給另一個函數進行處理。 這是我的代碼。

void displayAll(int p[][], char** e){
    int i, j;
    for(i = 0; i < numExperiments; i++){
    printf("\n%s: ", *(e+i)); //print experiment name
        for(j = 0; j < 10; j++){
            printf("%d ", *p[j]); //print all the data corresponding to above experiment name
        }
    }
}

char *experiments[20]; //20 char pointers to 20 experiment names
char charBuffer[1024]; //buffer to hold all of the experiment name values
char *currentLine = charBuffer; //holds the values of the current line read from stdin

int data[20][10]; // 20 arrays of 10 integer data
int intBuffer[10];
    int i = 0; //counter for outer while loop
    while(fgets(currentLine, 20, ifp) != NULL){ //while there is still data in stdin to be read

        experiments[i] = currentLine; //experiment[i] points to the same value as current line. Each value in experiments[] should contain pointers to different positions in the allocated buffer array.
        currentLine += 20; //currentLine points 20 characters forward in the buffer array.

        int j = 0; //counter for the inner while loop
        while(j<=0){ //while j is less than 10. We know that there are 10 data points for each experiment
        scanf("%d", &intBuffer[j]);
        data[i][j] = intBuffer[j];
        j++;
    }
    numExperiments++; //each path through this loop represents one experiment. Here we increment its value.
    i++;
}
displayAll(data, experiments);

我認為問題在於嘗試傳遞2d數組,盡管語法對我來說似乎正確,所以我覺得問題可能在於我對代碼的不同部分的誤解。 為什么他的數據通過不起作用?

在函數參數中使用2維數組時,必須給出其內部維度:

void displayAll(int p[][10], char** e)

外部尺寸是可選的。

您應該告訴定義中的函數,最后一個維度的大小。

這條線

while(j<=0){ //while j is less than 10. We know that there are 10 data points for each experiment

意味着它只會為每個循環讀取一個項目 - 它應該是

while(j<=10){ //while j is less than 10. We know that there are 10 data points for each experiment

一種方法是將指針傳遞給數組的第一個元素,同時將數組的寬度作為參數:

void displayAll(int *p, int w, char** e)

然后你可以使用寬度w來索引數組:

p[y*w+x]

(正如您所看到的,寬度是正確索引數組所必需的,這就是為什么您不能只傳遞多維數組並讓它在沒有此信息的情況下工作的原因 - C數組不包含有關其自身維度的信息。)

或者,如果函數只需要支持一種大小的數組,則可以直接在類型中給出寬度,並讓編譯器為您執行上述計算:

#define ARRAY_WIDTH 10
void displayAll(int p[][ARRAY_WIDTH], char** e)

(使用相同的宏ARRAY_WIDTH指定其他地方的寬度,而不是四處散布幻數10

C99引入了可變長度數組,也可用於此:

void displayAll(int w, int p[][w], char **e)

但是,這在編譯器中並不是完全可移植的,並且該功能在C11中是可選的。

暫無
暫無

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

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