Assignment to pointer in the update section create a Segmentation fault. Why?
int vars[5] = {0,1,2,3,4};
int* var = NULL;
for(int i = 0; i < sizeof(vars); i++, var = &vars[i]){
printf("%d \n", *var);
}
I'm expecting that var has actual value.
A for
loop has an initialization expression, a condition, and an increment. The increment is run after the loop runs for the first time. In this case:
for(int i = 0; i < sizeof(vars); i++, var = &vars[i]){
var
is only assigned to a non-null value after the loop runs the first time, at which point printf("%f \n", *var);
results in a null dereference (undefined behavior, in this case a segmentation fault). In addition to that, sizeof()
returns the number of bytes in an array, not the number of elements. This also would result in an out of bounds access as the loop terminates much later than it should, assuming sizeof(int) > 1
.
Try putting var = &vars[i]
in the condition statement, which runs before the first iteration instead of in the increment statement, which runs afterwards, and dividing sizeof(vars)
by sizeof(*vars)
to get the number of elements in the array instead of the number of bytes.
int vars[5] = {0,1,2,3,4};
int* var;
for(int i = 0; var = &vars[i], i < sizeof(vars)/sizeof(*vars); i++){
printf("%d \n", *var);
}