【发布时间】: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