我有如下所示的输入文件

5

8

10

实际上,我需要在上面的示例中读取文件的更多行。(之间没有空格。因此,我需要使数组的大小取决于文本文件的行。这是我使用的方法出现在r

#include "stdafx.h"
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

int _tmain(int argc, _TCHAR* argv[])
{
    FILE *test;
    int numbers[]={0};
    int i=0;
    char *array1;
    if((test=fopen("Input1.txt","r"))==NULL)
    {
        printf("File could not be opened\n");
    }
    else
    {
        array1 = (char*)malloc(1000*sizeof (char));
        if((test=fopen("Input1.txt","r"))==NULL)
        {
            printf("File could not be opened\n");
        }
        else
        {
            while(fgets(array1,(sizeof array1)-1,test)!=NULL)
            {
                numbers[i]=atoi(array1);
                i++;
            }
            for(i=0;i<sizeof(array1)-1;i++)
            {
                printf("%d\n",numbers[i]);
            }
        }
    fclose (test);
    }
    system("pause");
    return 0;
    free(array1);
}

最佳答案

您正在使用sizeof做它不能做的事情。sizeof array1是变量array1的大小。由于将其定义为char *,因此大小是指针的大小(在32位系统中为4,在64位系统中为8)。
您显然希望array1指向的已分配内存量。但是sizeof无法提供它。

您需要使用分配的大小-在您的情况下为1000。最好将其放在变量中,而不要在两个位置使用数字1000(因为如果更改一个,可能会忘记更改另一个)。

10-07 18:57
查看更多