Array of C structs

后端 未结 4 1589
面向向阳花
面向向阳花 2021-01-16 10:54

If I create a struct in C and want to add them to an array that is not set to a fixed size, how is the array created?

Can one create a tempStruct which is used on ev

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-16 11:30

    Yes, you can use a tempStruct during input which you add later to the array.

    If the size of the array is unknown, then you are in trouble. You must keep track of the array's size somewhere. Just have an integer variable that you change every time you change your array to keep track of your array's size.

    If the size of the struct is not known at compile time it is even more complicated. You either just store Pointers in the array which point to your actual struct elements in memory, or you have to keep track of the sizes of every struct in the array. In the later case you would have to do addressing in the array completely manually calculating a lot. While this is very memory efficient, it is also error prone and extremely hard to debug.

    OK. sample to create an array that hold your struct using pointers:

    struct MyStruct
    {
      /* code */
    }
    
    main()
    {
      counter = 0;
      struct MyStruct** array = malloc(counter);
      // Create new Element
      struct MyStruct myElement;
      myElement.someData = someValue;
    
      // Add element to array:
      array = realloc(array, sizeof(struct MyStruct*) * (counter + 1);
      array[counter] = &myElement;
      counter++;
    
      // Create yet another new Element
      struct MyStruct myElement;
      myElement.someData = someOtherValue;
      array = realloc(array, sizeof(struct MyStruct*) * (counter + 1);
      array[counter] = &myElement;
      counter++;
    
      // Now remove the last element
      free(array[counter -1]); // may have something more complicated than that, depending on your struct
      array = realloc(array, sizeof(struct MyStruct*) * (counter - 1);
      counter--;
    }
    

    this code is not tested!

提交回复
热议问题