【问题标题】:Can't pass a char array to a function无法将 char 数组传递给函数
【发布时间】:2014-04-03 13:56:15
【问题描述】:

我在将 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. 我知道已经有人问过类似的问题,但我根本不知道如何将那里的答案翻译成我的案例......)

【问题讨论】:

    标签: c char pass-by-reference


    【解决方案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 */
      

    【讨论】:

      【解决方案2】:

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

      当数组作为函数参数传递时,它们会自动转换为指向其第一个元素的指针。它看起来像传递引用,因为您可以修改指针指向的内容,但事实并非如此,它仍然是传递值,即指针本身的值。

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

      【讨论】:

        猜你喜欢
        • 2012-05-10
        • 1970-01-01
        • 1970-01-01
        • 2023-03-25
        • 2012-10-23
        • 2016-03-27
        • 1970-01-01
        相关资源
        最近更新 更多