in Programming in C
267 views
1 vote
1 vote
int A[]={0,1,2}

int *ptr1 = &A       // 1

int (*ptr2)[] = &A     // 2

what is the difference bw 1 and 2 in terms of accessing elements of array
in Programming in C
267 views

1 Answer

2 votes
2 votes

int A[]={0,1,2}; ====> By these line you are creating a array let Base address of array is 100 and size of int is 4 Bytes, therefore 

0 1 2
100 104 108

 

note that &A=100 and &A[0]=100 but A means Array and A[0] means element

to get difference btw those,

( & A[0] ) + 1 ===> points to next element of the Array (104 in your example)

but (&A)+1 ===> points to next Array ( Here we don't have next Array therefore garbage memory Address but the Address should be 112 in your example )



int *ptr1 = &A ; ===> declaring ptr is a pointer to int and store that Address of array A but note that ptr can hold integers only not array's therefore you get warning, actually we have to get compilation error but C is loosly therefore it get 100 and convert the address into integer but not array, therefore you can access next element by p+1. for getting value p[1] or *(p+1).

 

Correct Syntax is int *ptr1 = A ; ( due to A is collection of elements therefore A points to first element of the Array )
 

int (*ptr2)[] = &A ; ===> ptr2 is a pointer to Array of Integers, therefore &A is valid...

How to Access elements of Array?

note that de-referencing of ptr equivalent to A, i.e., *ptr = A

First get A ===> *ptr ===> get element * ( * ptr )

 

Better Understanding https://www.geeksforgeeks.org/complicated-declarations-in-c/

Better Understanding of Arrays https://www.youtube.com/watch?v=Lu_2WGzEDmM&index=33&list=PLsFENPUZBqipuTJXgm7xAOR0UnY_8OY07

Related questions