c初学者,矢量

Jou*_*uge 1 c vector

我是初学者,我有一个问题(像往常一样).我写了这个简单的程序:

 #include <stdio.h>
 #define SIZE 10

 main()
 {
    int vettore[9];
    int contatore1,contatore2;

    for(contatore1 = 0; contatore1 <= 9; ++contatore1)
    {
        vettore[contatore1] = contatore1*2;
    }

    printf("%d\n\n", vettore[9]);

    for(contatore2 = 0; contatore2 < 10; ++contatore2)
    {
        printf("%d\n", vettore[contatore2]);
    }

    printf("\n%d\n", vettore[9]);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

该程序的输出是:

18

0
2
4
6
8
10
12
14
16
9

10
Run Code Online (Sandbox Code Playgroud)

为什么vettore [9]的价值变化3倍?为什么它只在输出的第一行有正确的值?谢谢 :)

sim*_*onc 5

C数组基于零,因此9元素数组的有效索引为[0..8].您正在编写超出阵列末尾的内容.这有未定义的结果,但可能会破坏下一个堆栈变量.

更详细... vettore有9个元素,可以使用vettore[0]... 访问vettore[8].第一个循环的最后一次迭代写入vettore[9].这将访问超出数组末尾的内存.这会导致未定义的行为(即C标准未在此处指定预期结果),但很可能地址与地址vettore[9]相同contatore2,这意味着后一个变量被写入.

你在下一个循环中遇到类似的问题,它打印的元素多于vettorecontains.

您可以通过将循环更改为来解决此问题

for(contatore1 = 0; contatore1 < 9; ++contatore1)
for(contatore2 = 0; contatore2 < 9; ++contatore2)
Run Code Online (Sandbox Code Playgroud)

请注意,如果您更改为计算数组的大小,通过sizeof(vettore)/sizeof(vettore[0])在循环的退出测试中使用而不是硬编码,则会更安全9.