Kelevra
Kelevra

Reputation: 13

Initializing a 3-dimensional char-Array in C

I hope that you guys can help me with a problem I have.

For a little Project I have to initialize a 3 dimensional char-array, when I initialize it in the main it works without a problem, so I think that the problem lies more or less between my keyboard and chair ;)

I have seperated the initialization from the main to a seperated .c I will give you a glimpse of it:

/*database.c*/
#define PHRASE_NUM 6
#define PHRASE_LEN 100
#define PHRASE_TYPES 2

void initDatabase(char database[][PHRASE_TYPES][PHRASE_LEN]) {

/* At this point I get the error "error: expected expression before ']' token" */
database[][PHRASE_TYPES][PHRASE_LEN]= 
{
        {{"string 1.1"},{"string 1.2"}},
        {{"string 2.1"},{"string 2.2"}},
        {{"string 3.1"},{"string 3.2"}},
        {{"string 4.1"},{"string 4.2"}},
        {{"string 5.1"},{"string 5.2"}},
        {{"string 6.1"},{"string 6.2"}}
};

}

 /*main.c*/
#include "database.h"
int main (void)
{
    char database[PHRASE_NUM][PHRASE_TYPES][PHRASE_LEN];
    initDatabase(database);

    printf(database[1][0]);
    /* should return string 2.1  */

    return 0;
}

So as stated in the comment above i get the following error: "error: expected expression before ']' token". I have checked if I did something wrong with the general init. of the array but this works if I implement it directly in the main.

Upvotes: 1

Views: 1209

Answers (1)

MByD
MByD

Reputation: 137362

You can initialize arrays only at declaration, not afterwards.

What you can do is:

void initDatabase(char database[][PHRASE_TYPES][PHRASE_LEN]) {
    char temp_array[][PHRASE_TYPES][PHRASE_LEN]= 
    {
            {{"string 1.1"},{"string 1.2"}},
            {{"string 2.1"},{"string 2.2"}},
            {{"string 3.1"},{"string 3.2"}},
            {{"string 4.1"},{"string 4.2"}},
            {{"string 5.1"},{"string 5.2"}},
            {{"string 6.1"},{"string 6.2"}}
    };
    memcpy(database, temp_array, sizeof(temp_array));
}

Upvotes: 3

Related Questions