1

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.

1 Answer 1

3

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));
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, you just saved my evening! I now feel slightly embarrassed for forgetting such a crucial thing :/ I think it's time for me to read over some books again... ;) Thanks again an have a good weekend :)

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.