简体   繁体   English

遍历C语言中的数组

[英]Iterate through an Array in C

My code looks like this: 我的代码如下所示:

void main()
{
    int vect[10], i;

    for (i=0; i<5; i++)
        vect[i] = i*2;

    printf("Vector: ");

    for (i=0; i<10; i++)
        printf("%d ", vect[i]);

    printf("\n");

When executing it, it will always show me this kind of output: 执行它时,它将始终向我显示这种输出: 在此处输入图片说明

To make it just show the elements I entered (the first five; 0 2 4 6 8) I must use a counter or is there a way of telling it to only show me those elements? 为了使其仅显示我输入的元素(前五个; 0 2 4 6 8),我必须使用计数器,或者是否有办法告诉它仅显示这些元素?

Is there a reason why the elements 5, 6, 7 and 9 are always the same but the 8th changes every time? 有没有理由为什么元素5、6、7和9始终相同,但每次都会更改第8个元素? I rewrote the program to change how it shows the elements and it is the same way: it shows the five elements I entered, then three that remain always constant, then one that changes every time the program is executed and then a last constant one. 我重新编写了该程序,以更改其显示元素的方式,并且使用相同的方式:它显示了我输入的五个元素,然后三个始终保持不变,然后每次执行程序时都会更改一个,最后一个不变。 Why is this? 为什么是这样?

int vect[10] indices 5-9 are not initialised- you need to assign something to them otherwise they will (probably) return garbage, as this is undefined behaviour ( C99 standard, section 5.1.2 "Execution environments" ). int vect[10]索引5-9尚未初始化-您需要为其分配一些内容,否则它们将(可能)返回垃圾,因为这是未定义的行为( C99标准,第5.1.2节“执行环境” )。 You can also define vect as static, ie static int vect[10] , since static variables will be automatically initialised to 0, and a static int array will have all elements automatically initialised to 0. 您还可以将vect定义为静态,即static int vect[10] ,因为静态变量将自动初始化为0,而静态int数组会将所有元素自动初始化为0。

In your code, vect is an automatic local array which is not initialized explicitly upon definition. 在您的代码中, vect是一个自动局部数组,未在定义时显式初始化。 So, at that point, all the element values are indeterminate. 因此,在这一点上,所有元素值都是不确定的。

To quote C11 , chapter §6.7.9 引用C11第§6.7.9章

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.[...] 如果未自动初始化具有自动存储期限的对象,则其值不确定。[...]

In the first for loop, you only initialize 5 elements, the rest elements are uninitialized and they contains indeterminate values. 在第一个for循环中,您仅初始化5个元素,其余元素未初始化,并且它们包含不确定的值。

Trying to read indeterminate values invoke undefined behavior . 试图读取不确定的值会调用未定义的行为

Related, Annex J, same standard, for undefined behaviour 相关附件J,相同标准,用于未定义的行为

The value of an object with automatic storage duration is used while it is indeterminate. 具有自动存储持续时间的对象的值在不确定时使用。

Once your program exhibits UB, nothing is guaranteed. 一旦您的程序显示UB,就无法保证。

FWIW, void main() should at least be int main(void) . FWIW, void main()至少应为int main(void)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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