Ravi Chandra
Ravi Chandra

Reputation: 687

Automatic type casting of array pointer

I am trying to understand pointers and arrays with the following program.

#include <stdio.h>

int main(void) {
    int arr[] = {1, 2, 3, 4, 5};
    int *ptr = &arr;
    int *ptr1 = arr;
    int (*ptr2)[5] = &arr;
    int (*ptr3)[5] = arr;
    int *ptr4 = &arr[0];
    int (*ptr5)[5] = &arr[0]; 
    printf("%d %d %d %d %d %d\n",*(ptr+1), *(ptr1+1), *(ptr2+1), 
            *(ptr3+1), *(ptr4+1), *(ptr5+1));
    return 0;
}

In one of the previous questions, referring to arrays as pointers, I read that arr is a pointer to the first element where as &arr is a pointer to the entire array.

If we do pointer arithmetic on ptr and ptr1 as shown in the above program, they both yield the same results i.e both of them are pointers to integer because they are assigned to the variables of type int *.

However I created a pointer to an array of 5 elements ptr2 and assigned the value of &arr. If I try to increment ptr2, it is incremented by 5 elements as expected. The behavior is similar in case of ptr3, ptr4, and ptr5

[Edit] When I do int *ptr = &arr the pointer to the array is type casted to int * automatically? Can I assume that &arr, arr, &arr[0] expressions are actually same because they produce the same value? And the arithmetic on this value actually depends on the type of assigned variable?

Upvotes: 2

Views: 133

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134346

Well, no, &arr, arrand &arr[0] are not the same. To elaborate,

  • &arr is the pointer to the array, the whole array. You can refer to the data type, for better understanding. &arr is of type int (*) [5] here, i.e., the pointer to an array of 5 ints.

  • arr is the array name, which in certain cases, decay to the pointer to the first element of the array.

  • &arr[0] is the address of the first element of the array, under all circumstances.

Suggestion: enable all compiler warnings and it should tell you where you are going wrong.

So, according to the above understanding,

 int *ptr = &arr;

is wrong as they are not of compatible type. Same goes for

int (*ptr5)[5] = &arr[0];

hence, any operation you try to perform with those variables (and their results, if any) are not defined.

Upvotes: 2

hrishi
hrishi

Reputation: 433

No, &arr and arr are not same in C as arr is pointer to first element of arr and &arr is the pointer to arr itself. However arr and &arr[0] are acts as same as they both point to first element of array(still they are not exactly same). In other way you can understand is arr and &arr[0] point to a 4 byte location whereas &arr point to 5x4 bytes location hence they are different.

Upvotes: 0

Related Questions