1

for some odd reason when I run this code:

int func(int arr[],int n) {
    int a = *(&arr + 1) - arr;
    printf("%d",a);
}

I get an address,

and when I run the same code inside main I get the length of the array.

any idea why?

I ran it inside main and it gave me the length of an array, and when I ran it inside a function it gave me an address.

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
Rani Giro
  • 23
  • 4
  • 2
    When declared as an argument, `int arr[]` is the same as `int *arr`. So `&arr` is a pointer to a pointer (type `int **`). You then dereference it to get a pointer (of type `int *`). Once your array have *decayed* to a pointer, you can't use tricks like that (or `sizeof arr / sizeof *arr` which is even more common) to get the size of the array. – Some programmer dude Feb 19 '23 at 12:22
  • 1
    You may want to read this: [What is array to pointer decay?](https://stackoverflow.com/questions/1461432/what-is-array-to-pointer-decay) Note, however, that some of the information there only applies to C++, not C. – Andreas Wenzel Feb 19 '23 at 12:57

1 Answers1

3

This function declaration

int func(int arr[],int n){

is adjusted by the compiler to

int func(int *arr,int n){

On the other hand. the array passed to the function as an argument expression is implicitly converted to a pointer to its first element of the type int *.

So within the function you actually deal with a pointer instead of an array.

In any case the expression with pointers used in this line within the function

int a = *(&arr + 1) - arr;

is invalid and invokes undefined behavior.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335