Exforsys
+ Reply to Thread
Results 1 to 3 of 3

Puzzled on Output

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"; b = test(a); ...

  1. #1
    Adrian is offline Senior Member Array
    Join Date
    Apr 2006
    Answers
    124

    Exclamation Puzzled on Output

    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?


  2. #2
    hvg_99 is offline Junior Member Array
    Join Date
    May 2007
    Answers
    9

    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


  3. #3
    Rahulbatra is offline Senior Member Array
    Join Date
    Apr 2006
    Answers
    124
    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


    •    Sponsored Ads



Latest Article

Network Security Risk Assessment and Measurement

Read More...