I have two structs defined in exactly the same way. Printing out the pointer value of the int pointer within them gives (nil) for one and an actual pointer value for the other.
#include <stdio.h>
struct struct1_ {
int *intPtr;
};
struct struct2_ {
int *intPtr;
};
int main(int argc, char const *argv[])
{
struct struct1_ struct1;
struct struct2_ struct2;
printf("struct1.intPtr %p\n", struct1.intPtr);
printf("struct2.intPtr %p\n", struct2.intPtr);
return 0;
}
output:
struct1.intPtr 0x7ffca33a3f10
struct2.intPtr (nil)
gcc version 9.4.0 (Ubuntu 9.4.0-1ubuntu1~20.04.1)
What the heck is going on here?
CodePudding user response:
When a local variable is left uninitialized, it's value (or for a struct the values of its members) is indeterminate. So there's no guarantee that any particular value will be read.
In fact, in many cases doing so triggers undefined behavior.