I have following code snippet in understanding the working of pointer to character array of specific length, with the following sample code.
#include <stdio.h>
int main(){
char sports[5][15] = {
"cricket",
"football",
"hockey",
"basketball"
};
char (*sptr)[15] = sports;
if ( sptr+1 == sptr[1]){
printf("oh no! what is this");
}
return 0;
}
How sptr+1 and sptr[1] can be equal?As the first one means to increment the address,which is stored in sptr by one and the second one means to get the value at address stored in sptr + 1.
sptr is a pointer to array of 15 chars. After initializing it with sports, sptr is pointing to first element of sports array which is "cricket".
sptr + 1 is pointer to second element of sports which is "football" and sptr[1] is equivalent to *(sptr + 1) which is pointer to first element of "football", i.e,
sptr + 1 ==> &sports[1]
sptr[1] ==> &sports[1][0]
Since pointer to an array and pointer to its first element are both equal in value, sptr+1 == sptr[1] gives true value.
Note that the although sptr+1 and sptr[1] have same address value their types are different. sptr+1 is of type char (*)[15] and sptr[1] is of type char *.
While dereferencing the pointer compiler will do like this,
a[i] == *(a+i);
You can verify that using the printf statement.
printf("%p\n",sptr[1]);
printf("%p\n",sptr+1);
Refer this link.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With