One day a guy asked me how to print a 2d string array in C. So I coded an example for him. But just for curiosity, I examined the assembly code. In C both string[0][1] and *(*string + 1) are the same. But in reality, the compiler writes the assembly code in 2 different ways. If we use string[0][1] it will directly move the value from the stack. When we dereference a pointer *(*string + 1) it will actually dereference the address pointed inside the register. This happens only in the MinGW GCC compiler. I compiled this using the latest on Windows which is 8.2.0-3 by the time I am writing this.
The assembly code in the left is this one.
[code language=”C”]
#include <stdio.h>
int main() {
char *string[][2] = {
{"Osanda","Malith"},
{"ABC","JKL"},
{"DEF","MNO"},
};
printf("%s %s\n", string[0][0], string[0][1]);
}
[/code]
The assembly code on the right is this.
[code language=”C”]
#include <stdio.h>
int main() {
char *string[][2] = {
{"Osanda","Malith"},
{"ABC","JKL"},
{"DEF","MNO"},
};
printf("%s %s\n", **string, *(*string + 1));
}
[/code]
(more…)