Frage

C language

How can I send a struct pointer variable as argument to a function that is going to edit that struct variable?

I have the following struct in a separate header file:

typedef struct {
    unsigned int id;
    unsigned int value;
} type1;

typedef struct {
    unsigned int id;
    type1 children[32];
    unsigned int numChildren;
} person;

And I want to be able to do this:

void person_editID(person *p, unsigned int newID) {
    p->id = newID;
}

In this:

void function2() {
    person *p;
    person_editID(p,2);
    printf("Person ID: %d\n",p->id);
    person_editID(p,4);
    printf("Person ID: %d\n",p->id);
}

(The two functions are in separate files)

And have the result:

Person ID: 2
Person ID: 4

But with the code above there is an error:

SIGSEGV... bad addr 0x0 (dataseg); err 0x6 nopage write ...

Is it because function2 p is not initialized? If so, how can I initialize it?

War es hilfreich?

Lösung

Change this:

person *p;

To this:

person p;

And this:

person_editID(p,2);

To this:

person_editID(&p,2);
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top