开发者

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

开发者 https://www.devze.com 2022-12-18 15:31 出处:网络
#define STRMAX 50 struct Person { char sName[STRMAX]; int iAge; }; typedef struct Person PERSON; int main() {
#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开发者_StackOverflow社区 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)

0

精彩评论

暂无评论...
验证码 换一张
取 消