[英]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()
; 主要执行
function_foo()
;
The output will be 1? 输出将为1? There's no initialization for elements of matrix k.
矩阵k的元素没有初始化。 Maybe something with the length of int in memory?
也许内存中有int长度的东西?
I am new to C concepts, the pointers and everything. 我是C概念,指针和所有事物的新手。
It is undefined behaviour to evaluate k[8]
, since k
only has 8 elements, not 9. 评估
k[8]
是不确定的行为 ,因为k
仅包含8个元素,而不是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 uninitialized . You have to write to them first, or initialize the array, such as int k[8] = { 1, 2 };
.) (请注意,它甚至会是不确定的行为,以评估
k[0]
,..., k[7]
因为它们是未初始化的 ,你必须给他们写第一,或初始化数组,如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. 如果您在一周内再次运行此代码,则可能是42或当前存储在此特定内存地址上的任何其他内容。 Also a segmentation fault could be possible in this case.
在这种情况下,也可能出现分段错误。
You are stepping out of the bounds of the array k. 您正在跳出数组k的边界。
To access the last element of k try using function_math(k, 7)
要访问k的最后一个元素,请尝试使用
function_math(k, 7)
The array is also not initialized so the values inside will be undefined. 该数组也未初始化,因此其中的值将是不确定的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.