在迭代

时间:2015-11-28 18:31:47

标签: c arrays

我是C编码新手。为了学习我想要做的语言,遵循一点“程序”。

我想扫描输入,并将它们放入二维数组 - 但我现在知道我想要扫描/输入多少元素=我想动态创建二维数组。这就是问题所在。我知道如何动态创建1d数组,例如

  int MAX;
  int *arr;
  scanf("%d",&MAX);
  arr=(int*)malloc( Max * sizeof ( int ) )

我找到了如何分配2d数组,例如

  int X;
  int Y;
  int **arr;
  scanf("%d%d",&X,&Y);
  arr=(int*) malloc ( X * Y * sizeof ( int* ) )

但我没有找到我最需要的东西=创建2d数组并在每次添加新项目时增加其“内存或大小”。 例如 - 我想要实现的目标。

    int **arr;
    int index=1;
    int X;
    int Y;
    arr=(int *) malloc ( index * sizeof ( int ) );
    while (! feof ){
       scanf("%d%d",&X,&Y);
       if ( index > 1 ){
         index ++;
         arr=realoc( arr*, index * sizeof ( arr* ) )
         arr[iX][0]=X;
         arr[iX][1]=Y;


       } else{
      arr[iX][0]=X;
      arr[iX][1]=Y;
      index++;
    }

    }

这是我的尝试而且我失败了......如何动态地改变每个输入(或循环的每次迭代)的2d数组的大小 我知道this解决方案,但所有答案都与预定义的y-osis数组一起使用。例如arr [] [25]

1 个答案:

答案 0 :(得分:0)

首先你需要一个指针字段,指针字段中的每个指针指向矩阵的行/列的第一个元素。每次要向行/列添加值时,都必须使用realloc增加行/列。每次要添加新行/列时,都必须向指针字段添加一个指针。因此,您需要两个截断条件,一个用于行/列,另一个用于指针字段。

以下代码显示了如何实现的示例。但请注意,程序可能因分配错误而终止。

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

main(){
//numberofrows points to the pointers used for the columns countrows tells us how many pointers we have
char **numberofrows;
int countrows=0;
//countcolumns tells us how much memory has to be allocated for the current column
int countcolumns=0;
numberofrows=malloc(sizeof(char*));
//t is needed for the first run of the loop otherwise the program will likely terminate
int t=0;
//truncation condition: e signals the end of the usersinput
while(t==0||numberofrows[countrows-1][countcolumns-1]!='e'){
    countcolumns=0;
    countrows++;
    t=0;
    //allocation of new array and reallocation of pointer array
    numberofrows[countrows-1]=malloc(sizeof(char));
    *numberofrows=realloc(*numberofrows,sizeof(char*)* countrows);

    //truncation condition \n: end of current column, condition e: end of input for 2d array 
    while(t==0||(numberofrows[countrows-1][countcolumns-1]!='\n'&&numberofrows[countrows-1][countcolumns-1]!='e')){
        countcolumns++;
        //change for t to activate truncation conditions
        t=1;
        // info for what postion new value is needed realloc to make place for additional value and setting of new value
        printf("row: %d, column: %d\n",countrows,countcolumns);
        numberofrows[countrows-1]=realloc(numberofrows[countrows-1],sizeof(char)*countcolumns);
        numberofrows[countrows-1][countcolumns-1]=getchar();
        //clears input buffer
        if(numberofrows[countrows-1][countcolumns-1]!='\n')
            while(getchar()!='\n'){}

    }
}

//prints transposed 2d array    
int tc=0,k=0;
while(tc<countrows){
    k=0;

    while(numberofrows[tc][k]!='\n'&& numberofrows[tc][k]!='e'){
        printf("%c ",numberofrows[tc][k]);
        k++;
    }
    printf("\n");
        tc++;
    }


}