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.

Edited 4 Years Ago by DeanMSands3: n/a

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.

Comments
I was about to post something on malloc, but decided the poster wouldn't get it. Rock on, deceptikon.
This article has been dead for over six months. Start a new discussion instead.