我不明白我尝试使用文件中的数据初始化并填充动态2D数组的秘诀

问题描述 投票:0回答:1

第一篇文章。我正在尝试通过一个函数来初始化2D数组。在使用该函数之前,我不知道数组的维数,所以我认为必须使用malloc。此外,我尝试读取的数据都位于.txt文件中,因此我使用fscanf函数。这是肯定更易于理解的代码。

    typedef struct Level Level;   
    struct Level{
        int height;
        int width;
        int **matrix;
     };

     int main(){
     Level test;
     Level *testPtr=&test;
     getLvl(testPtr);
     int i,j;
     printf("height=%d,width=%d",test.height,test.width); //veryfing I get the right height and width
     for(i=0;i<test.height;i++){
         for(j=0;j<test.width;j++){
             printf("test[%d][%d]=%d\n",i,j,test.matrix[i][j]);//printing the value supposed to be there
          }
      }

     }
     void getLvl(Level *testPtr){
         FILE *doc=NULL;
         doc=fopen("doc.txt","r");  //open my file
         fscanf(doc,"%d",&testPtr->height);    //get the height and width
         fscanf(doc,"%d",&testPtr->width);
         test->matrix=malloc(sizeof(int*)*testPtr->height*testPtr->width);  //initialise the matrix as an array of pointer
         int i,j;
         for(i=0;i<testPtr->height;i++){
             test->matrix[i]=malloc(sizeof(int)*testPtr->width);   //allocate every elements of the array enough memory to store the data of every 
             for(j=0;j<test->width;j++){
                 fscanf(doc,"%d",matrix[i][j]);
              }
         }

     }

因此,当我尝试执行代码时,获取高度和宽度没有问题。但是,获取数组的值会使控制​​台崩溃。据我所知,这源于试图访问我无权访问的内存的问题。我的文档文件看起来像这样:

10
10
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1    
c arrays struct malloc scanf
1个回答
0
投票

此代码中有很多错误(不考虑逻辑)。首先在这里

     Level test;
     Level testPtr=&test;

我认为您的意思是Level *testPtr=&test;

您发送testPtr到功能getLvl而不是test的秒,testmain的局部变量,在getLvl中不可见。每次使用test->members时都是错误的。

并且在此fscanf(doc,"%d",&matrix[i][j];行中,您缺少)。并且您正尝试直接访问结构的一个成员,而不使用该结构的变量。这是错误的。

© www.soinside.com 2019 - 2024. All rights reserved.