C - 动态结构数组

标签 c arrays pointers dynamic structure

我有一段相当大的代码的问题。了解我自己,这是某种愚蠢的错误,或者更可能的是,缺乏对指针的理解。我真的需要一些帮助,所以如果有人能看一下我将非常感激!我现在就来解释一下。

这是我的编程课的一个程序。老师在一个txt文件中给了我们一个数字(N)和一个字母(X),并希望我们创建一个包含三个字段(int、char和float)的结构体,然后是四个函数:

函数 #1 将数字 N 作为参数,并为指向 N 个结构的指针数组动态分配内存。然后它将值分配给结构中的字段 - int 和 char 设置为随机值,float 字段设置为结构的编号。该函数返回数组的地址。

函数 #2 将创建的数组的大小(其中的指针数量)和指向该数组的指针作为参数,并删除该数组,释放内存。

函数 #3 将创建的数组的大小和指向数组的指针作为参数,然后使用冒泡排序基于 int 字段对结构进行排序

函数 #4 搜索结构并计算字母 (X) 在结构的 char 字段中重复的次数。

这是带有注释和错误的代码。请问,有人可以解释我做错了什么吗?老实说,我快没时间了,但我愿意熬夜来理解并解决这个问题。

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

 struct Foo {
 int fieldint;
 char fieldchar;
 float fieldfloat;
 };

 Foo *initialize(int N);
 int sort(int N, Foo *tablica);
 int count(int N, Foo *tablica, char*X);
 int deleting(int N, Foo **tablica);

 int main () {

      //this reads the number N and the letter to find from the .txt file:
      FILE *file = fopen("inlab01.txt", "r");
      int number;
      char letter[1];
      if (file == NULL) {
           printf("Error opening file");
           exit(-1);
      } 
      while (fscanf(file, "%d%s", &number, letter) != EOF);
      fclose(file);

      //creating the array
      //again, it's supposed to be an array of pointers to N structures:
      Foo *arr[number]; 
      *arr = initialize(number);

      //sorting:
      sort(number, *arr); //the program crashes at this function

      //counting how many times the given letter appears:
      //count(number, *arr, letter);

      //we're supposed to print the first 20 of the structures
      //this loop prints one structure and then the program crashes
      for(int i=0;i<20;i++) {
          printf("Structure %d:\nfield int:%d\nfield char:%c\nfield float:\f\n\n", i+1, arr[i]->fieldint, arr[i]->fieldchar, arr[i]->fieldfloat);
      }

      //deleting:
      deleting(number, arr);

      getch();
      return 0;
}

Foo *initialize(int N) { 
     Foo **array;
     array = (Foo **)malloc(sizeof(Foo) * N);
     srand( time( NULL ) );    

     for(int i=0; i<N; i++) {
          array[i] = (Foo*)malloc(sizeof(Foo));           
          array[i] -> fieldint = rand();  //random number
          array[i] -> fieldchar = ( char )( rand() % 24 ) + 65; //random letter
          array[i] -> fieldfloat=i;     
     }

     return *array; 
}

 int sort(int N, Foo *array) {  
     int temp;
     for (int i=0;i<N;i++){
         for (int j=N-1;j>=j;j--) {
             if(array[j].fieldint < array[j-1].fieldint) {
                 temp = array[j-1].fieldint;
                 array[j-1].fieldint = array[j].fieldint;
                 array[j].fieldint = temp;
             }
         }
     }
     return 0;
 }

 int count(int N, Foo *array, char*X){ 
     int counter = 0;
     for(int i=0;i<N;i++) {
         if (array[i].fieldchar == 'X') {
             counter = counter+1;
         }
     }
     return counter;
 }

 int deleting(int N, Foo **array) {
     for (int i=0;i<N;i++) {
         free(array[i]);
     }  
     free(array);
     return 0;
 }

整个程序都可以编译,但随后程序崩溃了,而不是做任何事情,真的。

请帮忙。

最佳答案

struct Foo 
{
    int fieldint;
    char fieldchar;
    float fieldfloat;
};

Foo **array;
array = (Foo **)malloc(sizeof(Foo) * N);

您正在用 C++ 编译此代码。如果您想使用C编译器,则必须将代码更改为以下内容:

struct Foo **array;

您可以在任何地方使用struct Foo,并且不需要该强制转换。或者使用 typedef

声明结构

其次,Foo **array用于分配二维数组。您分配二维数组的方式是错误的。另外,你只需要一个一维数组 Foo arr[number]

for (int j=N-1;j>=j;j--)

请注意,排序函数中存在错误 (j >= j) 始终为 true。修复排序函数,避免分配二维数组,就完成了。

int sort(int N, struct Foo *array)
{
    int temp, i, j;
    for (i = 0; i< N; i++) {
        for (j = i + 1; j < N; j++) {
            if (array[i].fieldint > array[j].fieldint) {
                temp = array[i].fieldint;
                array[i].fieldint = array[j].fieldint;
                array[j].fieldint = temp;
            }
        }
    }
    return 0;
}

int main()
{
    srand((unsigned)time(NULL));
    int number = 3;
    struct Foo arr[number];
    int i;
    for (i = 0; i < number; i++) {
        arr[i].fieldint = rand(); //random number
        arr[i].fieldchar = 'A' + (char)(rand() % 26); //random letter
        arr[i].fieldfloat = (float)i;
    }

    sort(number, arr);
    for (i = 0; i < number; i++)
        printf("Structure %d:\nfield int:%d\nfield char:%c\nfield float:%f\n\n",
            i + 1, arr[i].fieldint, arr[i].fieldchar, arr[i].fieldfloat);
    getch();
    return 0;
}

请注意,您的排序函数交换了 fieldintFoo 有其他成员,如果您的目标是交换对象,您可能需要交换所有成员。

关于C - 动态结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40333453/

相关文章:

c - 获取用户输入,将其添加到数组中正确的索引处(升序)

c - 指针数组 C - NULL POSITION

javascript - 更新 JSON 数组 (Mongoose) 内具体 JSON 对象中的特定字段

arrays - 查找并替换元胞数组中的值

php - JSON 字符串到 PHP JSON 数组

c++ - 具有模板化成员的类的地址出现奇怪的错误

C++ 将指针传递给模板类函数

c - MPI_Reduce w 用户函数和非连续数据

c - 使用 Fiddle 将 RUBY 数组传递到 C DLL

c - 在C中用循环填充函数数组