1

I am attempting to pass, by reference, a 1-D array of characters to a function. Here is the relevant code:

void function1();
void function2(struct template *);

struct template{
        char array[11];
};

function1()
{
    struct template myStruct = {0};  //initializing

    function2(&myStruct);
}

function2(struct template *myStruct)
{
    void writeToArray(char array[11]); //locally declaring a function

    writeToArray(myStruct->array);
}

void writeToArray(char array[11])
{
    /*** stuff ****/
}

Now, when debugging this code, I get an unexpected result. Once I have entered writeToArray(), I call

p sizeof(array)

which returns 4. Shouldn't a value of 11 be returned?

I am aware that the "sizeof" for all variables is statically set at compile time. So why is the compiler considering "char array[11]" of writeToArray() to be size==4?

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129

2 Answers2

0

When you declare void writeToArray(char array[11]), it is actually declaring: void writeToArray(char *array).

You can find more on this by looking up 'decaying to pointers'.

So when you do sizeof(array) you are getting the size of the pointer.

If you want to do maintain this array size, try using void writeToArray(char (&array)[11]) instead.

This is passing the array by reference then declaring it an array of size 11. It will return the value you are expecting from sizeof.

Note: Even if your way did work, you are hard-coding the value 11, so you would be better of just declaring a const value and forgetting about sizeof altogether. Alternatively, reconsider why you are hard-coding the size.

Dan McGrath
  • 41,220
  • 11
  • 99
  • 130
0

When you pass an array as an argument to a function, the starting address of the array is passed to the function. Here the reference is a specified memory location and it occupies 4 bytes of memory on your host system.

Balayesu Chilakalapudi
  • 1,386
  • 3
  • 19
  • 43