GeeksforGeeks » C/C++ Programming Questions

A hedge fund interview question: what's the output result? And explain why.

(5 posts)

Tags:

  1. aloe
    guest
    Posted 1 year ago #

    what's the output result? And explain why.
    #include <stdio.h>
    int main()
    {
    char *p;
    char buf[10] = {1, 2, 3, 4, 5, 6, 9, 8};
    p = (buf+1)[5];
    printf("%d \n", p);
    }

  2. Shekhu
    Member
    Posted 1 year ago #

    I got compilation error in below statement

    p = (buf+1)[5];

    The error message

    "invalid conversion from char' tochar*' "

  3. Shekhu
    Member
    Posted 1 year ago #

    I think the code can be corrected by putting a * before p. Like below code works and prints 9.

    #include <stdio.h>
    int main()
    {
    char *p;
    char buf[10] = {1, 2, 3, 4, 5, 6, 9, 8};
    *p = (buf+1)[5];
    printf("%d \n", *p);
    getchar();
    return 0;
    }

  4. Venki
    Moderator
    Posted 1 year ago #

    As I was emphasizing in previous posts, the code will not compiler due to type mismatch.

    The expression (buf+1) evaluates to pointer to char type and (buf+1)[5] evaluates to 5th 'char'acter of array pointed by the pointer (buf+1). Hence resulting type of the expression "(buf+1)[5]" is char, which we assigned to char pointer. This conversion is unusual in C/C++ programming. Results in compilation error. If you use explicit cast from char to char * to get rid of error, the code fails at runtime.

  5. fundoo
    guest
    Posted 1 year ago #

    I think the correct way is
    int main()

    {
    char *p;
    p=(char*)malloc(sizeof(char));
    char buf[10] = {1, 2, 3, 4, 5, 6, 9, 8};
    *p = (buf+1)[5];
    printf("%d \n", *p);
    getch();

    }
    o/p-9


Reply

You must log in to post.

RSS feed for this topic