Pointers and char[] in C [closed]

To know how all these three code blocks works, you got to start reading good C book specially array and pointers concept.

Case 1 :- In the below code block

int main(void) {
    char x[] = "gate2011";
    char *ptr = x;
    printf ("%s", ptr+ptr[3]-ptr[1]);
    return 0;
}

It looks like

 x[0]   x[1]   x[2]     x[3]   x[4]    x[5]     x[6]   x[7]    x[8]
 0x100  0x101  0x102   0x103   ..                                   -->(assume 0x100 is base address of x )
 ---------------------------------------------------------------------
| g   |   a   |   t   |   e   |   2   |   0   |  1   |   1   |   \0   |
----------------------------------------------------------------------
x
ptr (ptr = x, i.e ptr points to base address of x)

This

ptr+ptr[3]-ptr[1]) == 0x100 + ( 'e' - 'a' )
                   == 0x100 +  4
                   == 0x104

So when printf() executes it will start printing from 0x104 until \0, hence it prints 2011.

Case 2 :- In the below code block

int main(void){
        char x[] = "sanguineapp";
        char *ptr = x;
        printf ("%s", ptr+ptr[5]-ptr[2]);
        return 0;
}

It looks like

x[0]   x[1]   x[2]     x[3]   x[4]    x[5]     x[6]   x[7]    x[8] ..
 0x100  0x101  0x102   0x103   ..                                   --> (assume 0x100 is base address of x )
 ---------------------------------------------------------------------------------
| s   |   a   |   n   |   g   |   u   |   i   |  n   |   e   |   a   |  p  | \0  |
---------------------------------------------------------------------------------
x
ptr (ptr = x, i.e ptr points to base address of x)

This

ptr+ptr[5]-ptr[2] == 0x100 + ( 'i' - 'n' )
                  == 0x100 + ( -5) /* so it will try to access invalid memory i.e base address 5 */

So when printf() executes, since you are providing wrong address to printf(), o/p of this statement causes undefined behavior, you are lucky that it didn’t crashes.

Same happens in third case also.

Leave a Comment