This is a discussion on Puzzled on Output within the C and C++ forums, part of the Programming Talk category; My C code is as below: #include <stdio.h> int main() { char *a, *b; x = "WELCOME"; ...
|
|||||||
| Register | FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read |
|
|||
|
My C code is as below:
#include <stdio.h> int main() { char *a, *b; x = "WELCOME"; b = test(a); printf ("b = %s \n", b); return 0; } char* test(char *p1) { p1 += 3; return (p1); } The output I got was COME .I could not understand how COME was printed as output. Can someone explain me on the output evaluation? |
|
|||
|
Puzzled on output: it is not true
#include <stdio.h>
int main() { char *a, *b; a = "WELCOME"; b = test(a); printf ("b = %s \n", b); return 0; } char* test(char *p1) { p1 += 3; return (p1); } First of all you have used 'x' as a variable...which is wrong instead it must be a="WELCOME". you are calling a function called test where you are sending the pointer which is pointing to "WELCOME". *p1 is currently pointing to 'W' of "WELCOME" which is '0' since arrays in 'C' starts from 0; the body says p1 +=3; meaning you are incrementing p1 4 times i.e. p1=0, p1=1,p1=2 then 3 which means it currently points to 'C' of 'WELCOME". and now u are returning p1. and since the output is b=COME which is not a puzzle..it is so simple . I hope i have cleared your doubt. Regards, Gayatri |
|
|||
|
This is a nice question and program reflecting the basic concepts of pointers and strings. The base or the starting address of string is incremented by 3. Say for instance if the base address is 1000 then 1000+3=1003.The storage inside the memory of the string would be as below:
1000 - W 1001 - E 1002- L 1003- C 1004- O 1005- M 1006- E Since the current pointer now is placed in 1003 all characters from 1003 of the string gets printed and so you got output as COME |
![]() |
| Thread Tools | |
|
|
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Output of the Statement | Adrian | Oracle Database | 2 | 04-26-2008 04:40 AM |
| To get Output | Rahulbatra | C and C++ | 1 | 05-10-2007 09:23 AM |
| Control Output | caradoc | DB2 | 3 | 04-09-2007 08:59 AM |
| Reason for Output | cyrus | C and C++ | 1 | 01-14-2007 11:02 AM |
| C Programming - Managing Input and Output Operations | JobHelper | Career Advice | 0 | 04-15-2006 08:30 AM |