views:

259

answers:

5
#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?

+1  A: 

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 :)

+1  A: 

Change

PERSON *personen[1];

to

PERSON personen[1];

and use strcpy to copy the string.

strcpy(personen[0]->sName,"Pieter");
codaddict
+2  A: 

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

And like others have said, use the strcpy function!

batbrat
A: 

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 pouinter 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)

Toymakerii
A: 

Better use std::string, if you can use STL.

Use CString if you use MFC and/or ATL.

Use wxString if you use WX library.

But none of methods would work (including pointer, as a member variable), if you need to send data over network or need to save into binary file for later retrieval.

Ajay