Hello!

I have a problem. I can't use scanf() to set a value of the second member of the person struct. Why? I get an error that tells me "bad access".

int main(int argc, const char * argv[])
{
    
    struct Adress{
        char *street;
        char *postal;
        int zip;
    };

    struct Person{
        char *firstName;
        char *lastName;
        struct Adress home;
    };
    
    struct Person newPerson;
    
    printf("Enter your first name and last name: \n");
    scanf("%s %s", newPerson.firstName, newPerson.lastName);
    printf("Hello %s %s! \n", newPerson.firstName, newPerson.lastName);
    
}

You only have pointers. The memory space isn't allocated yet. If you were using arrays, that'd be different.

struct Adress{
        char street[32];
        char postal[32];
        int zip;
    };

    struct Person{
        char firstName[32];
        char lastName[32];
        struct Adress home;
    };

EDIT:
This might be helpful.
Stanford Explains Pointers.

[edit]what ^^^ said.

Uninitialized pointers are not pointers to infinite memory. You have to allocate memory before trying to write to it:

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

int main(void)
{
    struct Person
    {
        char *firstName;
        char *lastName;
    };

    struct Person newPerson;

    newPerson.firstName = malloc(50);
    newPerson.lastName = malloc(50);

    printf("Enter your first name and last name: \n");
    scanf("%49s %49s", newPerson.firstName, newPerson.lastName);
    printf("Hello %s %s! \n", newPerson.firstName, newPerson.lastName);
    
    free(newPerson.firstName);
    free(newPerson.lastName);

    return 0;
}

It's also best to check and see if malloc() returns a null pointer, but I won't complicate the example with that yet.

commented: I was about to post something on malloc, but decided the poster wouldn't get it. Rock on, deceptikon. +4

Tank you! :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.