C:读入整数数组的垃圾值

标签 c arrays garbage

我看了 [ Read list of numbers in txt file and store to array in C ] 来弄清楚如何将整数文件读入数组。

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

int second_array[100], third_array[100];

int main(int argc, char *argv[])
{
   int first_array[100]; 
   FILE *fp;

   fp = fopen("/home/ldap/brt2356/435/meeting_times.txt", "r");

   /* Read first line of file into array */
   int i = 0;
   int num;
   while(fscanf(fp, "%d", &num) == 1) {
      first_array[i] = num;
      i++;
   }

   /* Print contents of array */
   int j = 0;
   while(first_array[j] != '\0') {
      printf("%d", first_array[j]);
      j++;
   }
   printf("\n");

   fclose(fp);

   return(0);
}

文件看起来像这样:

5 3 2 4 1 5
2 2 4
7 9 13 17 6 5 4 3

数组打印正确,除了最后有一个垃圾值。示例输出如下所示:

5324152247913176543-1216514780

-1216514780 垃圾值从何而来?

最佳答案

int 数组不会有空字符,\0 在末尾。幸运的是,您有一个变量可以跟踪数组的大小 - i。你的第二个 while 循环应该有一个如下所示的条件:

while(j<i)

关于C:读入整数数组的垃圾值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26415565/

相关文章:

php - 传递 $_POST 值以输出各个结果信息

javascript - 垃圾收集跟不上 Buffer 的创建和删除

objective-c - 如何从 SQLite3 行中获取日期或日期时间?

c++ - 用 g++ .cpp 文件编译 gcc .o 文件

c - 扫视行为怪异

python - Numpy 两个二维数组的逐元素 isin

arrays - Angular-数组forEach索引

c - C 编程中未初始化的数组

c - 队列弹出一些垃圾值

c - 这种类型的双关语定义明确吗?