How can I make user enter custom message for the msgbuf.mtext? Whenever I try to change it manually I am getting following error:
struct msgbuf msg
expression must be a modifiable lvalue
What am I doing wrong?
struct msgbuf {
long mtype;
char mtext[80];
};
int main() {
int qid, opt;
int mode = 0;
int msgkey = 1234;
qid = msgget(msgkey, IPC_CREAT | 0666);
struct msgbuf msg;
msg.mtext = "hello";
msgsnd(qid, (void *) &msg, sizeof(msg.mtext), 0);
printf("sent: %s\n", msg.mtext);
return 0;
}
CodePudding user response:
The data member mtext
is declared as a character array.
char mtext[80];
Arrays are non-modifiable lvalues. You may not assign one array to another.
For strings you should use for example standard string function strcpy
declared in header <string.h>
strcpy( msg.mtext, "hello" );
Or you could initialize the data member mtext
in the declaration of the object msg
like for example
struct msgbuf msg = { .mtext = "hello" };
If you want to enter a string using scanf
you can write
scanf( "ys", msg.mtext );
or
scanf( " ys", msg.mtext );
or
scanf( "y[^\n]", msg.mtext );
or
scanf( " y[^\n]", msg.mtext );
Also in this call
msgsnd(qid, (void *) &msg, sizeof(msg.mtext), 0);
it seems you need to use expression strlen( msg.mtext )
instead of the expression sizeof(msg.mtext)
. And casting to void *
the expression &msg
is redundant. A pointer to any object type can be converted to a pointer of the type void *
.
Pay attention to that the data member mtype
was not initialized.