In for loop update statement has problems with pointer assignment in ansi c

55 Views Asked by At

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.

2

There are 2 best solutions below

2
CPlus On BEST ANSWER

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);
}
1
ptiza_v_nebe On

I think I have found myself at least some understanding. The main problem is that scope of var inside of for brackets is different as outside. Maybe it could be compared to lambdas with its possibility to capture variables.

Following code works as intent:

double vars[5] = {0,1,2,3,4};
int var_size = sizeof(vars)/sizeof(vars[0]);

double* var = NULL;
int i = 0;
for(var = &vars[0]; i < var_size; var = &vars[++i]){
    printf("%f \n", *var);
}