简体   繁体   English

c中的for循环返回错误值

[英]For loop in c returning wrong value

image of issue with output输出问题的图像

I'm reading a set of numbers from a file (1 2 3 4 5 6 7) and when I print them out in the while loop it returns the correct numbers.我正在从文件 (1 2 3 4 5 6 7) 中读取一组数字,当我在 while 循环中将它们打印出来时,它会返回正确的数字。 In the for loop directly below it, it's returning random numbers (under loop through array).在它正下方的 for 循环中,它返回随机数(在循环数组下)。 Anyone know what is going on?有谁知道发生了什么?

#include <stdio.h>

int main(int argc, char* argv[])
{
  if(argc != 2){
      printf("%s\n", "Wrong number of arguments");
  }
  else{
    char* filename = argv[1];
    printf("%s\n", filename);
    FILE* fp = fopen(filename, "r");
    int arrSize;
    int array[arrSize];
    int i = 0;

    fscanf(fp, "%d\n", &arrSize);

    printf("%d\n", arrSize);

    while (fscanf(fp, "%d", &array[i]) == 1) {
      printf("%d\n", array[i]);
      i = i+1;
    }

    
    printf("%s\n", "Loop through array");
    for (int j = 0; j < arrSize; j++) {
      printf("%d", array[j]);
      printf("\n");
    }

    fclose(fp);
  }
}

You have:你有:

int arrSize;
int array[arrSize];
int i = 0;

fscanf(fp, "%d\n", &arrSize);

When you define array , you have no idea what value is in arrSize ;当您定义array ,您不知道arrSize值是什么; it is uninitialized.它是未初始化的。

You need:你需要:

int arrSize;
int i = 0;

fscanf(fp, "%d\n", &arrSize);

if (arrSize <= 0 || arrSize > MAX_ARRAY_SIZE)
    …deal with error condition…

int array[arrSize];

You might want to think about writing the first loop as:您可能想考虑将第一个循环编写为:

for (int i = 0; i < arrSize && fscanf(fp, "%d", &array[i]) == 1; i++)
    printf("%d\n", array[i]);

This avoids overflowing the bounds of the array you have allocated.这避免了您分配的数组的边界溢出。 You then don't need the separate declaration of i either.然后您也不需要i的单独声明。 The braces are optional;大括号是可选的; I wouldn't use them for a single, simple statement like the printf() call, but many people always use them.我不会将它们用于像printf()调用这样的单个简单语句,但很多人总是使用它们。 The braces become necessary, of course, if the loop is revised to:当然,如果循环修改为:

for (int i = 0; i < arrSize; i++)
{
    if (fscanf(fp, "%d", &array[i]) != 1)
        break;
    printf("%d\n", array[i]);
}

It's good that you test for fscanf(…) == 1 ;测试fscanf(…) == 1很好; people often mistakenly test against EOF.人们经常错误地针对 EOF 进行测试。

Look at this piece of code.看看这段代码。

int arrSize;
int array[arrSize];
int i = 0;

fscanf(fp, "%d\n", &arrSize);

What do you think what will happen?你认为会发生什么? You are declaring an array without defining its size.您正在声明一个数组而不定义其大小。

int arrSize;
fscanf(fp, "%d\n", &arrSize);
int array[arrSize];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM