Question

I am having difficulty passing a char array to a function:

This is code is found inside a function, which calls another function createbitshape:

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

Here is 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);

The prototype is:

 void createbitshape(int, char[]);

When I run the code, I see two different addresses of bitshp:

bitshp inside: 0x7fff854d8b80
bitshp outside: 0x7fff854d8b70

How come ? Does createbitshape allocates another memory room ? How do I change this code such that createbitshape writes the content to bitshp defined in the calling function?

(p.s. I know similar questions have been already asked, but I simply don't get how to translate the answers there to my case...)

Was it helpful?

Solution

Your confusion is because the assumption is incorrect, there is no pass-by-reference in C, only pass-by-value.

When arrays are passed as function argument, they are automatically converted to a pointer that points to their first element. It looks like pass-by-reference as you can modify what the pointer points, but it's not, it's still pass-by-value, the value of the pointer itself.

That means the function argument bitshp is a new pointer, it's supposed to have a different address than the bitshp outside the function. But they do share the same value.

OTHER TIPS

Yu Hao answer is great, I'm glad you accepted it.

I'd like to complement it with a brief explanation on why the addresses differ inside and outside. Its a combination of two things:

  • Array variables decay to pointers when they are passed as function arguments:

    static size_t my_sizeof(char array[32]) {
        return sizeof(array);
        /* Always returns either 4 or 8 depending on your architecture */
    }
    
  • When you use the address-of operator on an array, it will return the same address:

    char array[8];
    printf("%p %p\n", array, &array);
    /* Will output the same value twice */
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top