Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion with string pointers [duplicate]

#include<stdio.h>
int main()
{
    switch(*(1+"AB" "CD"+1))
    {
        case 'A':printf("A is here");
            break;
        case 'B':printf("B is here");
            break;
        case 'C':printf("C is here");
            break;
        case 'D':printf("D is here");
            break;
    }
}

The output is: C is here.

Can anyone explain this to me its confusing me.

like image 390
rimalroshan Avatar asked Nov 30 '22 14:11

rimalroshan


2 Answers

First of all, string literals only separated by white-space (and comments) are concatenated into single strings. This happens before expression parsing (see e.g. this translation phase reference for more information). This means that the expression *(1+"AB" "CD"+1) is really parsed as *(1+"ABCD"+1).

The second thing to remember is that string literals like "ABCD" are really read-only arrays, and as such one can use normal array-indexing with them, or letting them decay to pointers to their first element.

The third thing is that for any array or pointer p and index i, the expression *(p + i) is equal to p[i]. That means *(1+"ABCD"+1) (which is really the same as *("ABCD"+2)) is the same as "ABCD"[2]. Which gives you the third character in the string. And the third character in the string is 'C'.

like image 99
Some programmer dude Avatar answered Dec 05 '22 07:12

Some programmer dude


In C, adjacent string literals, such as "AB" "CD", are concatenated. (This is a convenience that allows long strings to be easily broken up over multiple lines and enables certain features such as macros like PRIx64 in <inttypes.h> to work.) The result is "ABCD".

A string literal is an array of characters. In most circumstances, an array is automatically converted to a pointer to its first element. (The exceptions are in contexts where you want the actual array, such as applying sizeof.) So "ABCD" becomes a pointer to the A character.

When one is added to a pointer (to an element in an array), the result points to the next element in the array. So 1+"ABCD" points to the B. And 1+"ABCD"+1 points to the C.

Then the * operator produces the object the pointer points to, so *(1+"ABCD"+1) is the C character, whose value is C.

like image 34
Eric Postpischil Avatar answered Dec 05 '22 06:12

Eric Postpischil