简体   繁体   中英

Assign characters to arrow pointer in c

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.

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.


Alternatively, you can allocate the struct with automatic storage duration, which is simpler and less error-prone:

struct room bedroom;

and then assign it's address to the pointer:

stream = &bedroom;

This avoids the need for dynamic memory allocation, which you might fail to free() later on.


[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.

See also: Do I cast the result of malloc?

[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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM