arrayscstruct

Why can't I point to an array in an array?


struct page { 
   
   int a;
   int b;
};

page chp1p1 = { 1, 2 }; // chapter 1 page 1

page chp1[12] = {

   chp1p1

};

page chapters[14] = {
   
   chp1

};

int main(){

   page& currChp = chapters[0];
   page& currPart = currChp[0];

   printf("If we are here then no errors");
   return 0;

}

Error at currChp[0].

Tried point to an array in an array. Elements are structs. I just don't want to use a switch-case. From my perspective, all I am doing is point to an array inside of an array, by their reference. So I don't understand why it's an error.


Solution

  • Yours is a very, very basic beginner syntax question. Make sure to review your textbook materials.

    struct index
    {
      int chapter;
      int page;
    };
    
    struct index indices[2] =
    {
      { 0, 0 },
      { 1, 24 },
      // etc
    };
    

    However, it looks like you want a (chapter ⟶ page number) lookup.

    For this you only need an array of indices into the pages. int will do.

    Also, when you initialize an array statically, you can omit the number of elements in the array (because the compiler can figure it out for itself).

    #include <stdio.h>
    
    int chapter_to_page[] =
    {
      0,
      24,
      //... and so on
    };
    
    int main(void)
    {
      printf( "Chapter 1 begins on page %d\n", chapter_to_page[1] );
      return 0;
    }
    

    If you intend to do something like load a file with information about which pages individual chapters begin on then you will want to just have a large array and track its size:

    #define MAX_NUM_CHAPTERS 100
    int chapter_to_page[MAX_NUM_CHAPTERS] = {0};
    int num_chapters = 0;
    

    Adding a lookup to that is easy:

    chapter_to_page[num_chapters++] = 0;
    chapter_to_page[num_chapters++] = 24;
    // ... etc
    // be careful to not let `num_chapters` get bigger than `MAX_NUM_CHAPTERS`