0

Why am I getting this error and how to I resolve it?

void add(struct Data* data,char* name, char* hobbies[])
{
    size_t lenn=strlen(name);
    data->name=(char*)realloc(data->name,lenn+1);
    memcpy(data->name,name,lenn+1);

}


int main()
{
    struct Data data;
    s_init(&data);
    add(&data,"Jose",{"Sing","Run"});
    return 0;
}

Error:

ayuda.c:32:19: error: expected expression before ‘{’ token add(&data,"Jose",{"Sing","Run"});

Jean-François Corbett
  • 37,420
  • 30
  • 139
  • 188

4 Answers4

4

Use C99 compound literals to make the error go away:

add(&data, "Jose", (const char *[]){ "Sing", "Run" });

Also, please:

  1. use whitespace;
  2. pay attention to const-correctness (a pointer to string literal should be const char *, and likewise, your function should accept a const char *[] argument);
  3. and do NOT cast the return value of realloc()!
Community
  • 1
  • 1
1

You cannot put {"Sing","Run"} directly as parameter, you need to create an array then pass it as parameter, for example:

char* values[] = {"Sing","Run"};
add(&data,"Jose",values);
m0skit0
  • 25,268
  • 11
  • 79
  • 127
1

You can only use the {"...", "..."} as part of an array initialization. You cannot do it from inside the code. You can, however, access the elements later on after creating the array, using the var[x] statement, where x is the index of the element you are trying to access.

DerStrom8
  • 1,311
  • 2
  • 23
  • 45
  • "You can only use the {"...", "..."} as part of an array initialization" - this was only true until 1999. –  Dec 28 '13 at 21:15
  • You can't *only* use that code unless it's part of the initialization. If you're trying to do it from within the code you have to add in more statements. m0skit0 and my posts are still technically correct, but you can add code to the OP's that makes it possible – DerStrom8 Dec 28 '13 at 21:17
1

{"Sing","Run"} pass it as array

Moamen
  • 11
  • 2