Question

i came across something quite odd(for me at least), while i was reading a C tutorial:

void foo(char arr[]){

}


void main(){

  char old_buffer[100];

  foo(old_buffer);           //Working??!
  char arr2[] = old_buffer;  //Error!


}

The line with the error comment is clear to me, old_buffer is treated like an address so this can't work because the array is missing information how much memory should be allocated. But why is this working in the head of a function? Thanks for your support :)

Was it helpful?

Solution

The line with the error comment is clear to me, old_buffer is treated like an address so this can't work because the array is missing information how much memory should be allocated.

That's close, but it's not exactly what's happening: the line with the error is not syntactically correct - if you change it to

char *arr2 = old_buffer;

it will work. However, this would not be an array, it would be a pointer. It would allow array-like access, but it would not give you the correct value in the sizeof.

But why is this working in the head of a function?

Because when you pass an array to a function, the size is always ignored. It is said that the array decays to a pointer. In other words, your declaration is identical to this:

void foo(char *arr)

OTHER TIPS

old_buffer is the address of old_buffer[0], that is, it is &old_buffer[0]. char arr[] is equivalent to char *arr.

the array in c/c++ work as list of sequential pointers in MEM. the array name is variable that hold the address of first element in array. when we use the index to reach a value that stored at this index location the compiler know that, the value is stored in MEM location that equals to the address stored in array name added by index value . Ex :

A[0] ='v'
A = 0x000000
A[4] = 'c'

//it is location at  0x000000 + 4
//so the
 &A[4] = 0x000004 

.

char *arr2 = old_buffer; will be work at your code , and you can deal with arr2 as an array because it hold address of first element of pre-located array in MEM . this compiler way is the reason that get your code to work in the head of a function .

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top