For example:
struct A {
char *p0;
char *p1;
}
int main(int argc, char **argv){
char a=0;
char *b="W";
char c[]=['L','O','L',0];
struct A p[3];
p[0].p0=&a;
p[1].p0=b;
p[2].p0=c;
for(int i=0;i<3;i++){
p[i].p1=malloc(10);
strcpy(p[i].p1, p[i].p0);
}
I've read elsewhere that pointer comparisons aren't safe unless the pointers being compared point to the same array, block of memory, or only 1 after the array. However, my professor had no problems asking us in class what
- p[0].p0 < p[0].p1
- p[1].p0 < p[1].p1
- p[2].p0 < p[2].p1
Evaluates to. The answer is 0, 1, and 0.
I am theorizing that p[0].p0<p[1].p1
evaluates to 0 because p[0].p0
points to the memory location of the char a, which is stored on the stack which has a higher memory address that the space on the heap that p[0].p1
points to. This also why I think the expression p[2].p0 < p[2].p1
evaluates to 0, because p[2].p0
stores the memory location of the first element in the char array char[] c which is on the stack whereas p[2].p1
points to some space allocated on the heap (and therefore a lower memory address).
However, p[1].p0 < p[1].p1
evaluates to 1 because when char *
are declared pointing to string literals, the string literal is stored beneath the heap somewhere in the global/static variables and code section of the virtual memory space. Therefore the address it stores is below that of the address stored by p[1].p1 (which is the address of the space allocated on the heap).
I don't know, I can't think of any other explanation for
- The answers provided by my professor to the above 3 expressions
- The answers are confirmed by me running the 3 expressions on my machine
Conventionally I would've thought the answer is undefined or something. Is there some kind of exception to comparing pointers so long as they are stored in a struct? Otherwise why would my prof. pose this as a quiz/test question for us?