2016-09-09 63 views
0

我有一個函數C-迭代通過的空隙通過結構的數組*

struct Analysis reduce (int n, void* results) 

其中n是要分析的文件的數量,而且我通過分析結構的陣列結果。

分析結構的定義如下:

struct Analysis { 
    int ascii[128]; //frequency of ascii characters in the file 
    int lineLength; //longest line in the file 
    int lineNum; //line number of longest line 
    char* filename; 
} 

我投的無效*因爲如此,

struct Analysis resArray[n]; 
struct Analysis* ptr = results; 
resArray[0] = ptr[0]; 

,但我無法弄清楚如何通過resArray正確遍歷。我試過

for (i = 0; i < n; i++){ 
    printf("lineLength: %d\n", resArray[i].lineLength); 
} 

與n = 3,我得到垃圾值。 resArray [0]是正確的,但resArray [1]是一個非常高的數字,resArray [2]只是0.爲什麼resArray [1]或resArray [2]不會給出正確的值?如果我錯誤地增加了地址,那麼它會有意義,但我只是在某個索引處訪問數組。相當迷茫!

+1

嘗試'ptr [i]'而不是'resArray [i]'。 – BLUEPIXY

+1

使用'resArray [0] = ptr [0];'您將'results'的第一個元素複製到'resArray'的第一個元素。其他值未被初始化。 – LPs

+3

'爲什麼resArray [1]或resArray [2]不會給出正確的值 - 因爲沒有賦值給這些元素?所有你用'resArray [0] = ptr [0];'做了第一個元素。其他所有內容在該數組中都是* indeterminate *。但是......爲什麼把它們放在另一個陣列中呢?剛使用'ptr [i] .linelength'有什麼問題? – WhozCraig

回答

0

resArray [0]是正確的,因爲有「東西」:

resArray[0] = ptr[0]; 

其他要素都是垃圾,因爲你沒有設置有什麼價值。如果要複製整個陣列,則需要將複製方法更改爲:

for (i = 0; i < n; i++) 
{ 
    resArray[i] = ptr[i]; 
} 
-1

希望此代碼可以幫助您。

#include <stdio.h> 
#define d 3 
struct Analysis { 
    int ascii[128]; 
    int lineLength; 
    int lineNum; 
    char *filename; 
}; 

struct Analysis Analyses[d]; 

struct Analysis reduce(int n, void *results) { 

    struct Analysis resArray[n]; 
    struct Analysis *ptr = results; 

    for (int i = 0; i < n; i++) { 
     resArray[i] = ptr[i]; 
    } 

    for (int i = 0; i < n; i++) { 
     printf("lineLength: %d\n", ptr[i].lineLength); 
    } 

    return *ptr; 
} 

int main(void) { 
    struct Analysis a = {{5}, 2, 2, "George"}; 
    struct Analysis b = {{6}, 3, 3, "Peter"}; 
    struct Analysis c = {{7}, 4, 4, "Jane"}; 
    Analyses[0] = a; 
    Analyses[1] = b; 
    Analyses[2] = c; 
    reduce(d, &Analyses); 
    return 0; 
} 

您可以試試online

0

您不能直接指定數組的指針,因爲它們是不同的類型since array[n] is type struct analysis(*)[n] and ptr is type struct analysis(*)。查詢here瞭解更多信息。