c 中的数组和整数

问题描述 投票:0回答:1

在这个例子中,我想打印出数字

4
。这是我的问题的简化版本,但我的问题是相同的。为
b
分配一个值(在本例中为
4
)后,我想打印出数组的第 4 个元素,不是直接打印,而是使用单独的整数 (c)。然而,结果会打印出
0
。我不知道为什么。如果您能提供帮助,我会很高兴。提前非常感谢!

#include <stdio.h>
#include <stdlib.h>

int numbers[10], a, b, c;

int main() {
    for (a = 0; a < 11; a++) {
        numbers[a] = a;
    }
    b = 7 - 3;
    numbers[b] = c;
    printf("%d", c);
    return 0;
}
c assignment-operator
1个回答
1
投票

您应该读取它并将其存储到

c

,而不是设置数组的第四个元素
c = numbers[b];

另请注意,初始化循环运行得太远,分配了不存在的元素

numbers[10]

这是修改后的版本:

#include <stdio.h>

int main() {
    int numbers[10], a, b, c;

    for (a = 0; a < 10; a++) {
        numbers[a] = a;
    }
    b = 7 - 3;
    c = numbers[b];
    printf("%d\n", c);
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.