2014-03-02 48 views
2

我有傳遞char陣列功能難點:不能通過字符數組的功能

這是代碼被發現在函數內部,它調用另一個函數createbitshape

char ans[8]; 
char bitshp[8]; 
... 
fgets(ans, 10, stdin); 
createbitshape(random_num, bitshp); 
printf("bitshp outside: %p\n", &bitshp); 

這裏是createbitshape

void createbitshape(int n, char bitshp[]){ 
    int i, count; 
    count = 0; 
    i = 1<<(sizeof(n) * 2 - 1); 
    for (; i > 0; i >>=1) 
    { 
     if (n & i) /* check if any of the bits of n is not 0 .*/ 
      bitshp[count] = '1'; 
     else 
      bitshp[count] = '0'; 
     count++; 
    } 
    bitshp[8] = '\0'; 
    printf("bitshp inside: %p\n", &bitshp); 

的原型爲:

void createbitshape(int, char[]); 

當我運行的代碼,我看到bitshp的兩個不同的地址:

bitshp inside: 0x7fff854d8b80 
bitshp outside: 0x7fff854d8b70 

怎麼來的? createbitshape是否分配另一個內存空間?如何更改此代碼,使createbitshape將內容寫入調用函數中定義的bitshp

(PS我知道類似的問題已經被問過,但我根本沒有得到如何的答案有翻譯成我的情況下...)

回答

2

你的困惑是因爲假設是不正確,有在C中沒有傳遞引用,只能傳遞值。

當數組作爲函數參數傳遞時,它們會自動轉換爲指向其第一個元素的指針。它看起來像傳遞引用,因爲你可以修改指針指向的內容,但它不是,它仍然是值傳遞,指針本身的值。

這意味着函數參數bitshp是一個新的指針,它應該有一個不同於該函數外部的bitshp的地址。但他們確實有相同的價值。

1

餘昊答案很好,我很高興你接受它。

我想補充它,並簡要說明爲什麼地址內外不同。

  • 數組變量衰變時,他們被作爲函數的參數傳遞指針:

    static size_t my_sizeof(char array[32]) { 
        return sizeof(array); 
        /* Always returns either 4 or 8 depending on your architecture */ 
    } 
    
  • 當您在陣列上使用運營商的地址,就會返回它的一個兩件事情結合在相同地址:

    char array[8]; 
    printf("%p %p\n", array, &array); 
    /* Will output the same value twice */