I am new to C and I currently have some troubles. Please have a look at the following Code:
int main (int argc, char *argv[]) {
int j = 2;
int i = 100;
int *pi = &i;
pi = &j; //those 2 lines should do nothing, in my opinion
pi = &i; //
pi[1] = -4;
printf("i = %d, j = %d, *pi = %d\n", i, j, *pi);
return EXIT_SUCCESS;
}
The code fails with a SegFault. Some investigation with gdb:
(gdb) print &j
$1 = (int *) 0x7fffffffde80
(gdb) print &i
$2 = (int *) 0x7fffffffde84
However, without the 2 lines, the code works fine, because i and j seem to swap places in the memory - but why??
(gdb) print &j
$1 = (int *) 0x7fffffffde84
(gdb) print &i
$2 = (int *) 0x7fffffffde80
I asked my teacher, but unfortunately she had no idea.
Thanks in advance!!
EDIT: by working fine, i mean the printf prints: i = 100, j = -4, *pi = 100 -- pi[1] points on j, seemingly
The question is, why do those 2 Lines change anything?
pi[1]is undefined behavior, she's not a very good teacher.pi[1] = -4;is UB. You shouldn't useptr[ind]syntax to access just arbitrary locations. But your question, as you put it, is more about the way your particular compiler works, but not about how to do a proper C programming.