简体   繁体   中英

Error working with structs and pointer arrays: incompatible types in assignment

#define STRMAX 50

struct Person {
    char sName[STRMAX];
    int iAge;
};
typedef struct Person PERSON;

int main() {
    PERSON *personen[1];
    personen[0]->sName = "Pieter";
    personen[0]->iAge = 18;

    return 0;
}

This code generates an error on personen[0]->sName = "Pieter"; saying incompatible types in assignment . Why?

You don't want an array of pointers. Try
PERSON personen[1];

And like others have said, use the strcpy function!

Don't try to assign arrays. Use strcpy to copy the string from one array to the other.

... sName is an array of chars while "Pieter" is a const char* . You cannot assign the latter to the former. The compiler is always right :)

Change

PERSON *personen[1];

to

PERSON personen[1];

and use strcpy to copy the string.

strcpy(personen[0]->sName,"Pieter");

I agree with the above but I figured it was also important to include the "why"

int a;      // is an integer
int *b;     // pointer to an integer must be malloced (to have an array)
int c[];    // pointer to an integer must also be malloced (to have an array)
int d[5];   // pointer to an integer bu now it is initialized to an array of integers

to get b and c from simple pointers and give them memory to match d use the following to give them memory space

b = (int *) malloc(sizeof(int)*5);

where it casts the pointer returned from malloc to an int pointer, and creates a memory block of 5 times the size of an integer (thus it will hold 5 integers like d)

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