object_oriented_program's blog

By object_oriented_program, 9 years ago, In English

Hello all, recently I gave my C++ exam, I came across this question. I was unable to understand the logic.

Can anyone explain what happens inside foo() ?

Thanks for your help :)

#include <iostream>
using namespace std;

void foo(char **p);

int main()
{
    char *argv[] = {"ab","cd","ef","gh","ij","kl"};
    foo(argv);
    return 0;
}

void foo(char **p)
{
    char *t = (p += sizeof(int))[-1];
    cout << t << '\n';
}

Tags c++
| Write comment?
»
9 years ago, # |
Rev. 2   Vote: I like it +3 Vote: I do not like it

sizeof(int) == 4 for all modern systems.

p[i] equals to *(p + i). BTW, i[p] is also correct syntax.

p += 4;
char *t = *(p - 1); // t == p[3] == "gh"

Also, C++11 standart does not allow conversion from string literals (like "ab" in this code) to char * type. Tell it to your examiner.