如何将静态数组转换为动态?

时间:2014-05-12 11:56:57

标签: c arrays

我是C新手,我发现将程序从使用静态数组转换为使用动态分配数组太难了。

这是我的第3个程序(计算单词等形成.txt文件)。

那么我在程序中使用动态数组而不是静态数组需要做哪些更改?

这是我的代码的一部分:

int main(int argc, char *argv[]) { 
 FILE *myinput; 
 int count=0, a, userchoice,i=0, wrd,chrct,dfw,j,b,k;
 char arr[100][50], name[0][50];

  printf("Ender the name of the file you want to open: ");
  scanf("%s", name[0]);
  if((myinput = fopen(name[0], "r"))==NULL)
  {
    printf("Failed to open the file!");
    exit(1);
  }
  else
  {
printf("Reading %s.. Done!\n\n", name[0]);
printf("%s contein: ", name[0]);
  }
  while(wrd > 0)
    {
        wrd = fscanf(myinput, "%s",arr[i]);
        i++; //counting words in a line from txt file.
    }
  wrd = i;
    for(i = 0; i < wrd - 1; i++)
    {
        printf("%s ", arr[i]);
    }
printf("\n");
 while(userchoice!=5)
 {
    switch(userchoice=choice())  //choice() is a function just with a scanf.
      {



        case 1: wrd=countwords(myinput); break;
        case 2: chrct=coutnchar(myinput); break;
        case 3: dfw=diffrentwords(wrd,arr); break; 
        case 4: istograma(wrd,arr); break;
        default: break;
      }
 }
 results(wrd,chrct,dfw,myinput,arr,wrd);
 fclose(myinput); 
 return 0; 
}

以下是一些功能:

int choice(){
    int choice;
    printf("\n1: count words \n2: count characters \n3: count different words \n4: Istogramma\n5: Save and exit\n");
    printf("enter choice:\n");
    scanf("%d", &choice);
    return choice;
}

这是直方图函数:

istograma(int wrd, char arr[100][50]){
    int j, i = 0, len;

    for(i = 0; i < wrd - 1; i++){
      printf(" %s ",arr[i]);
      len=strlen(arr[i]);
      for(j=0; j<len; j++){
        printf("*");
      }
      printf("\n");
    }
}

3 个答案:

答案 0 :(得分:1)

char name[0][50];你的意思是[1] [50]吗?

代表char arr[100][50]

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

int main(void)
{
    char (*arr)[50];
    int i;

    arr = malloc(sizeof(*arr) * 100);
    if (arr == NULL) {
        perror("malloc");
        exit(EXIT_FAILURE);
    }
    for (i = 0; i < 100; i++)
        strcpy(arr[i], "test");
    for (i = 0; i < 100; i++)
        printf("%s\n", arr[i]);
    free(arr);
    return 0;
}   

答案 1 :(得分:1)

直接调试你的程序对你没有多大帮助,恕我直言。

我认为你需要一个例子来帮助你开始。

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

#define N 4

int main() {
    int a[N]; //I am a static array,
    // with four uninitialized elements.

    int i;

    for(i = 0; i < N; ++i)
        a[i] = i;

    // a[0] = 0, a[1] = 1, a[2] = 2, a[3] = 3.
    // Index starts from 0 and ends at N - 1 = 4 - 1 = 3.

    // print the array
    for(i = 0; i < N; ++i)
        printf("%d ", a[i]);
    printf("\n");

    // Now let's use a dynamic array

    // this will be the pointer to the array
    int* a_dyn;

    // here we allocate memory dynamically
    // how much memory? As many elements we need,
    // multiplied by the size of every element.
    // Here we need N elements, of type int,
    // thus N * sizeof(int)
    a_dyn = malloc(N * sizeof(int));

    // fill the array (like the static case)
    for(i = 0; i < N; ++i)
        a_dyn[i] = i;

    // print the array (like the static case)
    for(i = 0; i < N; ++i)
        printf("%d ", a[i]);
    printf("\n");

    // DO NOT FORGET TO FREE YOUR DYNAMIC MEMORY
    free(a_dyn);

    return 0;
}

研究示例,然后询问是否需要。

然后,尝试调试代码并在需要时报告。

提示:

enter image description here

这张照片实际上是你要创造的。

左边的1D数组是保存字符串的数组,类型为char*

正确的1D数组是实际的字符串,每个单元格都有一个字符。

所以,例如,如果你已经存储了字符串&#34; sam&#34;作为你的第一个字符串,你会得到这些:

a[0][0] = 's'
a[0][2] = 'a'
a[0][2] = 'm'
a[0][3] = '\0' <------Never forget the null terminator

如需更多信息,请点击here

答案 2 :(得分:0)

您应该使用malloc()。要调整数组大小,您应该使用realloc()

这是一个例子。随你的代码参考。

   char **arr, **temp;
   char string[50];
   int i;
   arr=NULL;
   temp=NULL;
   i=0;
   while(1)
   {
     wrd = fscanf(myinput, "%s",string);
     if(!(wrd>0))
     {
       break;
     }
     temp=(char **)realloc(arr,sizeof(char *)*(i+1));//With some enhancement
     //This increses size of the arr pointer with retaining the data and assigns it to "temp" pointer. Realloc copies data of arr in different memory having (i+1) size and stores it's reference in "temp".
     arr=temp;
     //we store the referene of temp in arr.
     arr[i]=(char *)malloc(sizeof(char)*(strlen(string)+1));
     //It allocates memory to the the arr[i]. You may compare it with your 2-d array but in dynamic array every row may have different size. We also save memory by doing this.
     strcpy(arr[i],string);
     //Copies "string"
     i++; //counting words in a line from txt file.
   }