There is a small program.

#include <stdio.h>

void f(char **p);

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

Assume the size of int is 4, I was asked to give the running result of the following code segment. In specific, I don't understand how to analyze

t=(p+=sizeof(int))[-1];

Recommended Answers

All 3 Replies

The program prints the last element of the array of chars that you give it.

t=(p+=sizeof(int))[-1];

Is what assigns t to the last element of the array of arrays of chars.

I'm not sure if that's exactly what you're asking, but if not, I'd like some more clarification so I could help.

Thanks.

since sizeof(int) = 4, so this line of code boils down to

t=(p+=4)[-1];

p should points to that char array, then the "(p+=4)" and "[-1]" got me lost.

The program prints the last element of the array of chars that you give it.

t=(p+=sizeof(int))[-1];

Is what assigns t to the last element of the array of arrays of chars.

I'm not sure if that's exactly what you're asking, but if not, I'd like some more clarification so I could help.

p+=4 causes p, which was originally a pointer to the first element of the array ("ab") to point 4 spots further (past the end of the array) so when it is indexed with -1 it points to the element before directly itself which would be the last element in the original array

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.