1

I am trying to run the following code and getting "gh" as the output. Please help me out, how are we getting this result.

void f(char **p) {
    char *t;
    t = (p += sizeof(int))[-1];
    printf("%s\n", t);
}

int main() { 
    char *arg[] = { "ab", "cd", "ef", "gh", "ij", "kl" };
    f(arg);
}

P.S. I am using the gcc compiler.

1 Answer 1

1

p+=sizeof(int) will make p to point sizeof(int) elements farther from the 0th element so that p+=sizeof(int) will give the address of the 4th element of passed array (assuming size of int 4 bytes on your machine). [-1] will decrement it by one letting t to point to the 3rd element which is "gh".

Sign up to request clarification or add additional context in comments.

2 Comments

p+=sizeof(int) will add sizeof(int) bytes to p: Not really, it will make p point sizeof(int) elements farther. p is a char **, so the elements are char*. The rest of your explanation is correct.
@chqrlie; I need some rest for today.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.