我不能让我的代码运行,我不知道什么是错的

时间:2017-07-24 12:52:53

标签: c

我正试图在c中解决uri在线判断(问题1318)的问题。

#include < stdio.h >

int main() {
    int N, M, a[M], i, j, fake;
    while (1) {
        scanf("%d %d", & N, & M);
        fake = 0;

        if (N == 0 && M == 0) {
            break;
        }
        for (i = 0; i < M; i++) {
            scanf("%d", & a[i]);
        }
        for (i = 0; i < M; i++) {
            printf("%d ", a[i]);
        }
        for (i = 0; i < M - 1; i++) {
            for (j = i + 1; j < M; j++) {
                if (a[i] == a[j]) {
                    fake = fake + 1;
                    break;
                }
            }
        }
        printf("%d\n", fake);
    }
    return 0;
}

此代码显示运行时错误...我不知道如何解决此问题,我不确定我的代码中是否有任何错误。

1 个答案:

答案 0 :(得分:1)

M 未初始化! 在创建数组M之前阅读a,或者使a足够大以包含所有可能的输入大小,并使用M来限制对a的访问。后者在竞争性编程中非常常见:创建一个足够大的静态数组,然后根据其他信息仅使用其中的一部分,例如M

无论如何,很容易发现错误,导致编译器警告Wall -Wextra: 以下是gccclangicc抱怨的内容。

 gcc   -Wall -Wextra -g -O3 -Wshadow  test.c
test.c: In function ‘main’:
test.c:7:1: warning: ‘M’ is used uninitialized in this function [-Wuninitialized]
 int N, M, a[M], i, j, fake;

             ^~~
 clang   -Wall -Wextra -g -O3 -Wshadow  test.c
test.c:7:13: warning: variable 'M' is uninitialized when used here
      [-Wuninitialized]
int N, M, a[M], i, j, fake;

           ^
test.c:7:9: note: initialize the variable 'M' to silence this warning
int N, M, a[M], i, j, fake;
            ^
         = 0
1 warning generated.
 icc   -Wall -Wextra -g -O3 -Wshadow  test.c
test.c(7): warning #592: variable "M" is used before its value is set
  int N, M, a[M], i, j, fake;