0

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

1
  • 1
    You need to allocate space for the struct first. Use malloc() Commented Oct 20, 2015 at 6:34

5 Answers 5

1

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.
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for this example!
Sure, glad I could help. Once you see all the pieces put together, it starts to make sense.
1

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

Comments

0

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;

Comments

0

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

Comments

0

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;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.