Ask your own question, for FREE!
Computer Science 20 Online
OpenStudy (anonymous):

char c[] = "CDAC2011"; char *p = c; printf("%s", p+p[3] - p[1]); what does the above fragment of C program print ?

OpenStudy (queelius):

Well, p[3] = 'C' which has a decimal (ascii code) value of 67. p[1] = 'D' which has a value of 68. So, 67 - 68 = -1. You're going outside the bounds of carray, so output is undefined.

OpenStudy (anonymous):

i got an output smthin like ~CDAC2011

OpenStudy (anonymous):

the only explanation i can think of is p[3] only has the offset from p instead of the exact adress

OpenStudy (anonymous):

nice question tho...

OpenStudy (queelius):

It's pointer arithmetic. The expression, "p + p[3] - p[1]", can be analyzed as follows: Take the memory address of "p", and then add some offset to it as specified by "p[3] - p[1]". As I explained previously, p[3] evaluates to 67 and p[1] evaluates to 68, therefore p[3] - p[1] evaluates to -1. So, -1 is our offset. This is actually before the starting address (as determined by the pointer "p") of the character array, so the answer is the output from this program is undefined. It depends on the undefined behavior of what is at the location which is before the character array.

OpenStudy (anonymous):

i dint understand why p[3]-p[1]= -1..........size of char is 1 so...that must be -2?

OpenStudy (anonymous):

and my program evaluates p[0]:00000043 p[1]:00000044 p[2]:00000041 p[3]:00000043

OpenStudy (queelius):

43 (hexadecimal, base 16) is equivalent to 67 (base 10), so that output you posted looks correct. The reason why p[3] - p[1] = -1 is due to this one reason: p[3] = 'C', which is a character. A character is just a way of interpreting a string of bits. This string of bits also represents a base 2 number, which is 67 for 'C'. Likewise, p[1] = 'D'. This is another character, and its string of bits encodes the number 68. That's where I get 67 - 68 = -1. That's all there is to it. When we create a pointer to a location at p - 1, where p is a pointer pointing to the start of the character array "CDAC2011", we end up pointing at a location, in contiguous memory, immediately before (1 byte) this character array. That's why my answer is that the output of the program is undefined -- we do not know what is at that location (or if it's even addressable) -- it depends on the particular runtime circumstances, compiler settings, operating system, etc.

OpenStudy (anonymous):

ok u mean to say that the entire thing is coz of the ascii values?

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!