Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How pointer to array of character behaves?

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.

like image 690
OldSchool Avatar asked Feb 21 '15 12:02

OldSchool


2 Answers

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 *.

like image 125
haccks Avatar answered Oct 14 '22 14:10

haccks


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.

like image 25
Karthikeyan.R.S Avatar answered Oct 14 '22 15:10

Karthikeyan.R.S