arrayscfor-looppointersimplicit-conversion

Is the & operator is essential to use as address operator


#include<stdio.h>
int main()
{
    int a[5]={5,10,15,20,25};
    int *p;
    int i;
    p=a;
    for (i=0;i<=5;i++)
    {
        printf("the address of the %d is = %d\n",*p,p);
        p++;    
    }
return 0;
}

In my program i do not even know that what was happening there because if put the address of operator in seventh line of the code which is =(p=&a) else I do not put = (p=a) the address of operator the answer of the running time of the both the case are same.

I was expecting that may be the answer is different in both cases but on both time the answer is same.


Solution

  • i do not even know that what was happening there because if put the address of operator in seventh line of the code which is =(p=&a) else I do not put = (p=a) the address of operator the answer of the running time of the both the case are same.

    It is because arrays decay to the reference to its first element. When you use & you get the same reference but it has a different type.

    int main(void)
    {
        int array[5];
    
        int *pointer_to_int = array;
        int *pointer_to_int1 = &array[0];
    
        int (*pointer_to_array)[5] = &array;
    
        printf("%p %p %p %p %zu\n", (void *)pointer_to_int, (void *)pointer_to_int1, (void *)(pointer_to_int + 1), (void *)(pointer_to_int1 + 1), sizeof(*pointer_to_int));
        printf("%p %p %zu\n", (void *)pointer_to_array, (void *)(pointer_to_array + 1), sizeof(*pointer_to_array));
    }
    

    When you run the posted program you will get the result (the actual addresses can be different):

    0x7ffef9ea1320 0x7ffef9ea1320 0x7ffef9ea1324 0x7ffef9ea1324 4
    0x7ffef9ea1320 0x7ffef9ea1334 20
    

    as you can see the pointer arithmetics behaves differently.