Search code examples
carraysmultidimensional-arrayragged

Ragged array in C


I've been handed a microcontroller project that is in C. I am an accomplished programmer, but not in this language. I 'think' my problem is related to C syntax (and my lack of understanding) and not the microcontroller compiler, so I will ignore the compiler issues for the sake of brevity.

I am attempting to use a Jagged/Ragged array to store font information for quick recall to be displayed on a LCD. There are other ways to attack this problem, but I have reasons for wanting to stick to this concept.

Let's assume for this example that there are only three glyphs (characters) in my font. What is unknown, is the length of each row that defines that glyph. Examples:

The glyph {A} would need this data: {65,8,12,1,0,0x18, 0x3C, 0x66, 0xC3, 0xC3, 0xC3, 0xC3, 0xFF, 0xFF}

The glyph {'} would need this data: {39,2,3,4,9,0xC0,0xC0, 0xC0}

The glyph {.} would need this data: {46,2,2,4,0,0xC0,0xC0}

With that in mind, here is my code.

//This is where I attempt to make my Jagged array.
 char X,Y, LeftOffSet, BaseOffSet;
 char * font[3]={{46,2,2,4,0,0xC0,0xC0},
                {39,2,3,4,9,0xC0,0xC0, 0xC0},
                {65,8,12,1,0,0x18, 0x3C, 0x66, 0xC3, 0xC3, 0xC3, 0xC3, 0xFF, 0xFF}};

//None of these assignments work properly.
 LeftOffSet=font[0][0];  // expected assignment = {46}
 LeftOffSet=font[1][4];  // expected assignment = {9}
 LeftOffSet=font[2][1];  // expected assignment = {8}

Does this code seem functional? I seem to be throwing an error that is difficult to trap. The assignments are not working as expected. When the compiler hits the first one, it resets the project.

Thanks in advance for your help.


Solution

  • If you really need a ragged array, then in order to build it using this in-line syntax you need a modern C compiler that supports compound literals

    char *font[] = { 
      (char []) {46,2,2,4,0,0xC0,0xC0},
      (char []) {39,2,3,4,9,0xC0,0xC0, 0xC0},
      (char []) {65,8,12,1,0,0x18, 0x3C, 0x66, 0xC3, 0xC3, 0xC3, 0xC3, 0xFF, 0xFF}
    };
    

    If your compiler does not support compound literals, you have no choice but to define the inner arrays as separate named objects

    char row0[] = {46,2,2,4,0,0xC0,0xC0},
         row1[] = {39,2,3,4,9,0xC0,0xC0, 0xC0},
         row2[] = {65,8,12,1,0,0x18, 0x3C, 0x66, 0xC3, 0xC3, 0xC3, 0xC3, 0xFF, 0xFF},
         *font[] = { row0, row1, row2 };
    

    Your original code is not valid C. If it compiles, it is only due to some compiler extension, which does not do what you think it does.

    P.S. Same problem as 'C' Segmentation fault with 2d array