C程序中scanf单独输入列表元素并输出的问题

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

我正在尝试制作一个程序,将元素分别输入到列表中,但不知何故它只运行到第二个元素,我不知道为什么。

#include <stdio.h>

int main() {
    int n; 
    int arr[n];
    scanf("%d", &n);
    
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    for (int x = 0; x < n; x++) {
        printf("%d", arr[x]);
    }
    return 0;
}
5
1
2
12
--------------------------------
Process exited after 1.99 seconds with return value 0
Press any key to continue . . .

这是我最初得到的。我尝试在第二个

\\n
中添加一个
scanf
字符,但它给了我这个。

5

1

2

3

12

\--------------------------------

Process exited after 5.1 seconds with return value 0

Press any key to continue . . .
c input scanf
1个回答
0
投票

我建议启用警告。如果您使用 gcc,请使用

-Wall -Wextra -Werror
,这将强制您删除所有警告,否则程序将无法编译。

当你编译你的程序时,你将得到:

<source>:5:5: warning: 'n' is used uninitialized [-Wuninitialized]
    5 |     int arr[n];
      |     ^~~

这意味着您需要先分配一些值(例如使用

scanf
)。否则,您的代码会调用未定义的行为,并且无法预测代码的行为。

还要经常检查

scanf

的结果
int main(void){
    int n; 
    if(scanf("%d",&n) == 1)
    {
        int arr[n];
        
        for(int i = 0; i<n;i++){
            if(scanf("%d",&arr[i]) != 1) 
            {
                printf("Error scanning the value at index %d. Exiting\n", i);
                return 1;
            }
        }
        for(int x = 0; x<n;x++){
            printf("%d",arr[x]);
        }
    }
    return 0;
}

https://godbolt.org/z/Y481vcM1c

© www.soinside.com 2019 - 2024. All rights reserved.