简体   繁体   中英

why does this C code outputs 1

Is there any reason why:

void function_foo(){
    int k[8];
    function_math(k, 8);
}

void function_math(int *k, int i){
    printf("value: %d", k[i]);
}

The main execute function_foo() ;

The output will be 1? There's no initialization for elements of matrix k. Maybe something with the length of int in memory?

I am new to C concepts, the pointers and everything.

It is undefined behaviour to evaluate k[8] , since k only has 8 elements, not 9.

There is little point arguing about the consequences of undefined behaviour. Anything could happen. Your program is not well-formed.

(Note that it would even be undefined behaviour to evaluate k[0] , ..., k[7] , since they are unini­tia­lized . You have to write to them first, or initialize the array, such as int k[8] = { 1, 2 }; .)

This is the value which is at the memory position after the last element of your declared array.

If you run this code in a week again, it could be 42 or anything else which is stored at this time on this specific memory address. Also a segmentation fault could be possible in this case.

You are stepping out of the bounds of the array k.

To access the last element of k try using function_math(k, 7)

The array is also not initialized so the values inside will be undefined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM