c - 麻烦 : C Declaration of integer array of unknown size

标签 c arrays compiler-errors

我需要使用 scanf 函数读取用户输入的未知数量的各种数字。这仅仅意味着各种整数的数量由用户通过发送尽可能多的数字来确定。请注意,我直接读取了数字(我必须这样做),如以下代码所述:

int main(void)
{
    int numbers[];
    int error = 0;

    int i = 0;
    while(scanf("%i", &numbers[i++]) == 1);

    for(int i = 0; i < sizeof(numbers) - 1; ++i) {
        if(numbers[i] < -10000 || numbers[i] > 10000)
        {
            printf("%i%s", numbers[i], ", ");
        }
        else
        {
            printf("%s", "\b\b\nError: Error: Vstup je mimo interval!\n");
            // Means "Input is out of range!".
            // We have to write exact output to terminal as stated in HW.
            i = sizeof(numbers);
            error = 1;
        }
    }

    ...
}

int error其实是一个boolean值,不过我懒得实现boolean库,所以定义成整数:D

但是,问题出在别处。编译器向我抛出一个错误:

main.c:7:9: error: array size missing in ‘numbers’
     int numbers[];
                ^

看起来 C 程序需要知道数组的可分配大小。我已经查看了其他人在那里共享的一些代码,以找出我需要实现的基础知识,并且在搜索数组大小问题时,我发现了这个问题:

C - Declaring an array with an undefined value

但是对于直接输入未知数量的数字,并没有解决数组大小未知的问题。我找不到我需要解决的地方。我试图定义数组的最大大小以容纳最多 999 个数字,但随后编译器向我抛出此异常:

main.c:50:23: error: iteration 999u invokes undefined behavior [-Werror=aggressive-loop-optimizations]
             if(numbers[j] > 0)
                       ^
main.c:48:9: note: containing loop
         for(int j = 0; j < sizeof(numbers); ++j)
         ^

用于数字统计的每个循环都相同(总数、最大值、最小值、赔率、偶数、正数、负数、它们的百分比和平均值)。这意味着该数组的大小严格为 999 个数字,其余数字为零。我找到了一个 malloc 函数,但不明白它的用法:(

最佳答案

“我需要使用 scanf 函数读取用户输入的各种数字的未知数量。”是一个糟糕的设计目标。

任何允许外部接口(interface)无限制地输入任何量输入的程序都是黑客攻击。

健壮的代码将用户输入限制在大量但合理的输入量内。好的代码会将上限编码为常量或宏。

使用 scanf() 并不是读取用户输入的最佳工具。
推荐 fgets() 读取 。 (此处未显示。)

#include <stdio.h>
#include <ctype.h>

// find the next character without consuming it.
int peek_ch(void) {
  unsigned char ch;
  if (scanf("%c", &ch) == 1) {
    ungetc(ch, stdin);
    return ch;
  }
  return EOF;
}

#define INPUT_N 1000
void foo(void) {
  int input[INPUT_N];
  size_t n = 0;

  // Read 1 _line_ of input using `scanf("%d", ....)` to read one `int` at a time
  for (n = 0; n < INPUT_N; n++) {
    int ch;
    while (((ch = peek_ch()) != '\n') && isspace(ch))
      ;
    // %d consume leading white-space including \n, hence the above code to find it.
    if (scanf("%d", &input[n]) != 1) {
      break;
    }
  }

  // TBD: Add code to handle case when n == N

  for (size_t i = 0; i < n; i++) {
    printf("%zu: %d\n", i, input[i]);
  }
}

关于c - 麻烦 : C Declaration of integer array of unknown size,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40193126/

相关文章:

C:在函数中通过引用传递二维数组以及如何在函数内部使用它们

c++ - 如何优化 3d 复杂 <double> 数组的 'for loop' 以提高 C++ 中的速度

arrays - 如何在 Swift 2 中初始化二维数组?

c# - 检查字符串是否包含任何字符串数组值,然后获取子字符串

c++ - 用多个文件编译c++程序

c - 如何在 Windows 上编译 C 完美最小哈希库?

c - 存储 gsl 矩阵的外部结构

c - Makefile,添加位于父目录中的头文件(不允许在内部移动!)

c++ - 为什么我不能在C++中填充此2D数组?

java - "non-static variable this cannot be referenced from a static context"错误