struct room
{
char venue[15]; //variable
}
*stream;
.
.
.
void idealounge(){
int i,idealounge[10];
char room1[10]="MMLC";
*** ** stream->venue = room1;*****
}
This is a room booking system.
The name of the room called MMLC.
I expect it can store "MMLC" to stream->venue but it shows errors like "incompatible values" etc.
CodePudding user response:
struct room
{
char venue[15]; //variable
}
*stream = NULL;
void idealounge() {
int i;
int idealounge[10];
char room1[10]="MMLC";
stream = (struct room *)malloc(sizeof(struct room));
strcpy(stream->venue, room1);
}
You should write this way.
CodePudding user response:
The statement:
char venue[15];
declares venue
to be an array of size 15 of char
. Then,
char room1[10]="MMLC";
initialises the first 4 bytes of room1
with the string literal "MMLC"
, setting the rest to \0
.
Then,
stream->venue = room1;
is invalid, because venue
is an array, not a pointer. Arrays are not modifiable l-values. You can't assign arrays like this.
If you want to copy the contents of room1
to the contents of venue
, use standard strcpy()
.
That being said,
struct room
{
char venue[15]; //variable
}
*stream;
only allocates space for the pointer, which is uninitialized and isn't pointing to anything meaningful. So first allocate memory and initialise the pointer:¹
stream = malloc (sizeof (struct room));
Then check if it succeeded:²
if (!stream) {
perror ("malloc()");
/* handle error here...*/
}
Now perform the string copy.
[1] — NB that I do not cast the result of malloc()
. malloc()
returns a generic void *
, or void
pointer, which is automatically promoted to the correct type. So there's no need to cast, and doing so might hide a potential bug.
[2] — POSIX-compliant systems set errno
on malloc()
failure, the above code snippet assumes it does. But you may not wish to take it for granted, and handle the error in another way.
CodePudding user response:
I See, i think the error you are getting is because you are trying to assign a string to a pointer. The variable stream->venue is a pointer to a character, but you are trying to assign it a string. To fix this, you can use the strcpy function to copy the string to the pointer.
You can solve with this:
strcpy(stream->venue, room1);
Please note that this is just a simple example, in real life scenarios you'll need to take care of the buffer overflow issue, so instead of strcpy, you can use strncpy or snprintf to avoid buffer overflow. Also before assigning value to the struct member, make sure it is pointing to a valid memory location.
stream = (struct room*)malloc(sizeof(struct room)); strcpy(stream->venue, room1);