Hi,

I am new in C, trying to create a simple C file, that assign a value for a struct member with the type of string. I can't figure out why it said error : string.c:20: error: expected expression before ‘{’ token, but I don't find any syntax error..

#include <stdio.h>
#include <stdlib.h>

typedef struct _str {
	char *s;
	int len;
} str;

typedef struct create_session {
    str mouse;
} create_session; 

void bzero (void *__s, size_t __n) __THROW __nonnull ((1));

int main()
{
 	create_session *msg_p = 0;
	create_session msg;
 	bzero(&msg, sizeof(create_session));
 	msg.mouse = {"1234567",7};
	msg_p = &msg;
	return 1;
}

Can anyone help me with this error?

thank you

Edited 5 Years Ago by reza.adinata: n/a

With gcc (I'm not sure about other compilers since I think this is an extension) you can do this in one shot. For instance:

typedef struct _str {
   const char * s;
   int len;
} str;

typedef struct cs {
   str mouse;
} cs;

int main () {
   cs msg = {
      .mouse = { "1234567", 7 }
   };
   /* ... */
}

However, to use the initializer syntax you need to do so when you declare the object; it is not legal to use it to assign to an existing object as you are attempting to do.

int main () {
   cs msg = {
      .mouse = { "1234567", 7 }
   };
   /* ... */
}

Hm, it works. But I don't understand above about this way of assigning value (in line 3 above) for the struct member (you have array inside array? no need to allocate memory?)
Can you point out, which term I can use to google about this kind way of assigning value inside a struct member? usually we assign just with (dot) isn't it?

Thank you

Hm, it works. But I don't understand above about this way of assigning value (in line 3 above) for the struct member (you have array inside array? no need to allocate memory?)
Can you point out, which term I can use to google about this kind way of assigning value inside a struct member? usually we assign just with (dot) isn't it?

There is no need to allocate memory as the character array ( "1234567" ) is const and provided at compile time (it actually ends up in a different location than memory provided at runtime). That also means that you can not modify that memory, either. If you are looking to assign an array that you can modify you will need something like

int main () {
   char buff[255] = {0};
   create_session msg = {
      .mouse = { buff, 255 }
   };
   /* ... */

You will not be able to use dynamic memory approaches with the above syntax.

If you want to understand more about the assignment syntax used here (the .member_name = ... ) you can google for designated initializer syntax if you want more details.

This question has already been answered. Start a new discussion instead.