Steven
Steven

Reputation: 9

How do I initialize members of a struct that is pointed to by a pointer?

I have the following struct in C:

typedef struct
{
    int age;
    char name[20];  
} Person;

in the main() I have:

Person *person;

person->age = 21;

This causes a segmentation fault, I have tried Googling but the resources that I have found do not have the struct declared as a pointer. I need this struct to be declared as a pointer so that it can be passed into another function. How would I properly access the members of this struct? (I also need to do this for char).

Upvotes: 0

Views: 81

Answers (5)

David C. Rankin
David C. Rankin

Reputation: 84521

It is fairly straight forward, declare a pointer to struct, then allocate with malloc and assign/copy values:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    int age;
    char name[20];  
} Person;

void agingfunction (Person **p)
{
    (*p)->age = 25;
}

int main (void) {

    Person *p = malloc (sizeof *p);
    if (!p) return 1;

    p->age = 5;
    strncpy (p->name, "Charles Darwin", 20);

    printf ("\n %s is %d years old.\n", p->name, p->age);

    agingfunction (&p);

    printf ("\n %s is now %d years old.\n", p->name, p->age);

    free (p);

    return 0;
}

Output

$ ./bin/structinit

 Charles Darwin is 5 years old.

 Charles Darwin is now 25 years old.

Upvotes: 1

Magisch
Magisch

Reputation: 7352

If you want to use this pointer, you need to allocate memory with malloc first. Like so:

Person *person = malloc(sizeof(Person));

But in your code you can also do without the pointer, by declaring person normally, like this:

Person pers;
pers.age = 21;
Person* pointer = &pers;

Upvotes: 0

Humam Helfawi
Humam Helfawi

Reputation: 20264

In the main do:

Person *person=malloc (1 * sizeof (Person ));
person->age = 21;

You need allocate a real place in the memory for your object. Then, you can deal with it

Upvotes: 0

Lundin
Lundin

Reputation: 213276

You need to allocate memory for the struct somewhere. If you have a function like void func (Person* p); then you pass a struct to it like this:

Person person;
func(&person);

or equivalent:

Person person;
Person* ptr = &person;
func(ptr);

Upvotes: 1

Sunil Bojanapally
Sunil Bojanapally

Reputation: 12658

You have to allocate memory for your struct instantiation as:

Person *person = malloc(sizeof(Person));

else you can also declare as

Person person;

and assign values as,

person.age = 21;

Upvotes: 0

Related Questions