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

4 Answers 4

2

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

And like others have said, use the strcpy function!

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

Change

PERSON *personen[1];

to

PERSON personen[1];

and use strcpy to copy the string.

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

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.