为什么程序在 fscanf 之后崩溃

Why program crashes after fscanf

I'am trying to read a data from a textfile with fscanf but after readData function program is crashing. It's not entering the loop statement. In the console there is just printing data is read. When i tried to reading data in main it's working but i need to read in function.

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

void readData(int array[10][3]);

int main(void)
{
    int data[10][3],i;
    
    readData(data);
    
    for(i=0; i<10; i++)
    {
        printf("%d %d %d \n",data[i][0],data[i][1],data[i][2]);
    }
}

void readData(array[10][3])
{
    int i;
    
    FILE *ptr = fopen("phonedata.txt","r");
    if(ptr == NULL)
    {
        printf("There is no file");
    }
    else
    {
        printf("Data is read");
    }
    
    while(fscanf(ptr, "%d %d %d",&array[i][0],&array[i][1],array[i][2]) != EOF);
    {
        i++;
    }
}

对于初学者,您忘记在函数定义中指定参数的类型

void readData(array[10][3])

你需要写

void readData(int array[10][3])

您在函数中使用了未初始化的变量 i

int i;

你必须写

int i = 0;

您还必须删除 while 循环后的分号

    while(fscanf(ptr, "%d %d %d",&array[i][0],&array[i][1],array[i][2]) != EOF);

而且条件最好写成

    while( i < 10 && fscanf(ptr, "%d %d %d",&array[i][0],&array[i][1],array[i][2]) == 3)

并且您需要将 while 循环放在 else 语句中

else
{
    printf("Data is read");

    while( i < 10 && fscanf(ptr, "%d %d %d",&array[i][0],&array[i][1],array[i][2]) == 3)
    {
        i++;
    }
}

并且您应该 return 从函数中填充的“行”数。

并且在退出函数之前必须关闭文件。

fclose( ptr );