2012-04-07 78 views
1

我使用一個函數來顯示指針指向的內存內容塊。 但沒有得到所需的輸出,我是新來的,請糾正我,如果我錯了。 當我輸入大小= 3,元素= 1,2,3,我得到輸出= 1只。在函數中使用指針指針的正確方法是什麼?

下面的代碼:

#include <stdio.h> 
#include <stdlib.h> 

void merge(int **arr1); 

int main(void) { 
    int size1; 
    printf("Give me the size of first array\n"); 
    scanf("%d", &size1); 

    int *arr1 = malloc(size1*sizeof(int)); 
    int *p1=arr1; 
    printf("Give me the elements of first array\n"); 
    int index1; 
    for(index1 = 0 ; index1<size1; index1++) 
    scanf("%d", p1++); 

    merge(&arr1); 
    return; 
} 

void merge(int **arr1) { 
    while(**arr1) //**arr1 is the content of the passed array, if there 
        // is an int in it, print that out and increment to next one 
    { 
     printf("%d", **arr1); // ** is the content and * is the address i think, right? 
     *arr1++; 
    } 
} 
+4

你得到了什麼輸出?你期望什麼?你到目前爲止做了哪些調試? – 2012-04-07 20:54:16

+2

請格式化您的代碼。 – 2012-04-07 20:54:58

+0

對不起,我編輯它 – 2012-04-07 20:57:24

回答

3

merge()代碼期望數組零終止。調用代碼沒有這樣做,所以行爲沒有指定(當我嘗試你的代碼時,我得到了段錯誤)。

的另一個問題是,你應該把周圍*arr1括號:

(*arr1)++; 

當我用這個修改就可以運行你的代碼,並在最後一個元素輸入零,你的代碼運行正常。

+0

對,所以我想檢查是否有任何有效的指針值,應該填寫while語句? – 2012-04-07 21:05:26

+0

@qwrqwr一種方法是在'malloc'中分配一個額外的元素,並在循環後面放入零。當然,這可以防止用戶輸入零。如果這是一個問題,可以使用另一個數字作爲「警衛」,或者將size1作爲第二個參數傳遞給merge。 – dasblinkenlight 2012-04-07 21:07:37

+0

所以你說沒有辦法檢查該元素是否有效,而不使用額外的大小參數? – 2012-04-07 21:11:24

相關問題