This is purely theory based, but I have this code:
int i = 3, k[] = {2, 4, 6, 8, 10, 12}, *x = &i, *y = k;
double d = 1.5;
struct point_tag {
int x, y;
char *name;
} pt[] = {{200, 40, "begin"}, {300, 100, "end"}}, *pp = pt;
and these two expressions:
pt[i--].y 50
which causes undefined behavior at run time
*(*pp.name 2)
which does not compile
I would just like to know why the top one can not run and why the bottom one does not compile, even though *((*pp).name 2)
does.
CodePudding user response:
pt[i--].y 50
which causes undefined behavior at run time
The array pt
has the size of 2, because you added two initializer items. This results in valid index values as 0 and 1. i
has an initial value of 3. You just access the array out of bounds.
*(*pp.name 2)
which does not compile
The operator preceedence favors .
before *
.
CodePudding user response:
You declared the array pt
as having 2 elements. The variable i
is initialized by the value 3
int i = 3,...;
So this expression with the subscript operator
pt[i--].y 50
accesses memory beyond the array because the valid range of indices for the array is [0, 2)
.
As for this expression
*(*pp.name 2)
then it is the same as the expression
*(*( pp.name ) 2 )
As the variable pp
is a pointer you may not apply the dot operator.
You need to write at least
*( ( *pp ).name 2)