简体   繁体   中英

Trouble with allocating structure variable with memory spaces and initialization

I am using visual C++ 6.0 to practice pointer staff, the following is my code:

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

typedef struct 
{
    char first_name[50];
    char middle_name[50];
    char last_name[50];
    int height;
    int weight;
}people;

int main()
{
    //declare a people structure pointer
    people *ppl_ptr;

    //allocate memory space for people structure
    ppl_ptr = malloc(sizeof(people));

    //check if you run out of the heap
    if(ppl_ptr==NULL)
    {
        printf("Out of memory!\n");
        return 0;
    }

    //initialize the unname people varible 
    (*ppl_ptr)={"bla","bla","bla",192,58};



    return 0;
}

but I got a syntax error: C:\\C Practice\\ch14.c(30) : error C2059: syntax error : '{' Error executing cl.exe.

and if I replace (*ppl_ptr)={"bla","bla","bla",192,58};

with something like (*ppl_ptr).first_name="bla";

I will get a different error:

ch14.c
C:\C Practice\ch14.c(30) : error C2106: '=' : left operand must be l-value
Error executing cl.exe.

and this error msg doesn't really make sense to me ... does this ever occur to anyone of you? Please let me know why it is giving me this error msg. Thanks in Advance.

Try accessing the structure properly:

char* bla_str_ptr = "bla";
[...]
strcpy(ppl_ptr->first_name, bla_str_ptr);
strcpy(ppl_ptr->middle_name, bla_str_ptr);
ppl_ptr->height = 123;
[...]

You could also write an initialization function with this signature:

void ppl_init(char* first_name, char* middle_name, [...])

In C90 you cannot use { } in assignments; only in initialization (ie when providing initial values to a variable in the same command as you are declaring the variable).

In C99 you could write (*ppl_ptr)=(people){"bla","bla","bla",192,58}; , but VC++ 6.0 is too old to support that.

What you can do is make another variable using initialization, and then copy using = :

people x = {"bla","bla","bla",192,58}; 
*ppl_ptr = x;

Some tips:
1. Always intialize a ponter to null else it may contian garbage value which if unknowingly accessed could cause problem.

people *ppl_ptr = NULL;

2. (*ppl_ptr).first_name="bla";
a) With the malloc, 50 character space is already allocated to it. So if you replace it with the address of "bla", you will be causing memory leak. Luckily, you have the l-value error to avoid such issue.
b) An Lvalue is an expression that can appear on the left-hand side of an equal sign, ie something that can be assigned a value.

In standard C, the = {} syntax is supported for initialization only, not for assignment after initialization. Use a loop to copy into (*ppl_ptr) , element by element.

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