0

I'd like to create a render table function in C, probably the worst language to do it.

I have a little problem initializing a table with is a bidimensional array of string, that make it a tridimensional array of char.

I am not able to initialize a tridimensionnal array that way:

char *table[][] = { 
    { "hello", "my", "friend" },
    { "hihi", "haha", "hoho"},
    NULL
};

But I get the error

test_table.c:8:11: error: array type has incomplete element type ‘char *[]’
     char *table[][] = { 

Can C compiler compute the lengths of all the dimensions ?

I also have tried to declare it as table[][][] and all the possible variants with *....

2
  • 3
    The array dimensions except the first must be fixed (specified). Use char *table[][3], or perhaps char table[][3][7];. Commented Mar 31, 2016 at 20:18
  • Too bad the compiler can't compute it himself, it would not be that hard. Thank you for the help. Commented Mar 31, 2016 at 20:41

2 Answers 2

1

The array dimensions except the first must be fixed (specified). Use char *table[][3], or perhaps char table[][3][7]:

#include <stdio.h>

int main(void)
{
    char *table1[][3] =
    {
        { "hello", "my", "friend" },
        { "hihi", "haha", "hoho"},
    };

    char table2[][3][7] =
    {
        { "hello", "my", "friend" },
        { "hihi", "haha", "hoho"},
    };

    for (int i = 0; i < 2; i++)
        for (int j = 0; j < 3; j++)
            printf("[%d][%d] = [%s]\n", i, j, table1[i][j]);

    for (int i = 0; i < 2; i++)
        for (int j = 0; j < 3; j++)
            printf("[%d][%d] = [%s]\n", i, j, table2[i][j]);

    return 0;
}

Output:

[0][0] = [hello]
[0][1] = [my]
[0][2] = [friend]
[1][0] = [hihi]
[1][1] = [haha]
[1][2] = [hoho]
[0][0] = [hello]
[0][1] = [my]
[0][2] = [friend]
[1][0] = [hihi]
[1][1] = [haha]
[1][2] = [hoho]

There are other ways to do it too, such as using C99 'compound literals':

#include <stdio.h>

int main(void)
{
    char **table3[] =
    {
        (char *[]){ "hello", "my", "friend" },
        (char *[]){ "hihi", "haha", "hoho" },
        NULL,
    };

    for (int i = 0; i < 2; i++)
        for (int j = 0; j < 3; j++)
            printf("[%d][%d] = [%s]\n", i, j, table3[i][j]);

    return 0;
}

Output:

[0][0] = [hello]
[0][1] = [my]
[0][2] = [friend]
[1][0] = [hihi]
[1][1] = [haha]
[1][2] = [hoho]
Sign up to request clarification or add additional context in comments.

1 Comment

I like the C99 'compounds literal' way, good trick ! Thanks !
0

See code below:

char *first[] = { "hello", "my", "friend" };
char *second[]  = { "hihi", "haha", "hoho" };
char **table[] = { first, second, NULL };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.