无法将char数组传递给函数

时间:2014-03-02 17:57:23

标签: c char pass-by-reference

我很难将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

(p.s。我知道已经提出了类似的问题,但我根本不知道如何将答案翻译成我的案例......)

2 个答案:

答案 0 :(得分:2)

您的困惑是因为假设不正确,C中没有传递引用,只传递值。

当数组作为函数参数传递时,它们会自动转换为指向其第一个元素的指针。它看起来像pass-by-reference,因为你可以修改指针指向的内容,但它不是,它仍然是值传递,指针本身的值。

这意味着函数参数bitshp是一个新指针,它应该具有与函数外部的bitshp不同的地址。但它们确实具有相同的价值。

答案 1 :(得分:1)

俞浩的回答很棒,我很高兴你接受了。

我想补充说明地址和外部地址不同的原因。它结合了两件事:

  • 当数组变量作为函数参数传递时,它们会衰减为指针:

    static size_t my_sizeof(char array[32]) {
        return sizeof(array);
        /* Always returns either 4 or 8 depending on your architecture */
    }
    
  • 当您在数组上使用address-of运算符时,它将返回相同的地址:

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