C language quiz
29Oct07
Let’s see how good is your knowledge of the C language: ¿can you tell me what does the following snippet print?
#include <stdio.h>
int main(int argc, char **argv) {
char *p = "hello";
printf("%c\n", 2[p]); /* Attention here! */
return 0;
}
I know what the explanation is, if no one is able of telling why this snippets behaves the way it does, I will post the solution here in a week or so
P.S: I can guaranteee that it is a valid C program, and it even compiles passing -Wall and -pedantic to GCC.
Filed under: Posts | 12 Comments
Tags: art, devel
mmm…
*p is a array of chars, and if you print the second element of array it prints “l” because an array stat count in cero. Is it?
You are right, it prints out “l”, but maybe you haven’t noticed this small difference: it is printing “2[p]” and not “p[2]”…
actually there is no meaning of 2[p] in C as such……
so compiler which ever it may be treat it as p[2] only……
It prints the ‘l’ . That is, the character can occupies the single Byte of Address. 2[p] is tells at the 2nd index of the address of the p[0] value.
It will print ‘l’. Because ‘2[p]‘ & ‘p[2]‘ having the same meaning in C.
answer is l
there is an error in this program
yes it is print p also .there is no problem in this program
here p is the base address of character array.so the address of p[2] is evaluated as p+2 , which is equal to 2+p. so 2[p]
gives same result as p[2]. that is ‘l’
its l
In program it is declared that p is an array of characters.2[p] means p[2] which is “l” so it prints “l”only.