0

I not entirely sure how to phrase this, but can't figure out how to access a struct pointer within another struct. How would I print the values in struct first_name *hello, given the structs below. I can't figure out the syntax.

struct first_name
{
    char *word
    int number
};

struct last_name{

    struct first_name *hello

    int num2

};

1 Answer 1

1

You are missing the semicolons in the structures:

Correct would be

struct first_name
{
    char *word;
    int number;
};

struct last_name{
    struct first_name *hello;
    int num2;
};

You can access the members like any other members of the structure.

struct first_name fn = { .word = "Hello", .number = 23 };

printf("word: %s, number = %d\n", fn.word, fn.number);


struct last_name ln = { .hello = &fn, .num2 = 11 };

printf("name: %s, number: %d, num2: %d\n", ln.hello->word, ln.hello->number, ln.num2);

The output would be:

word: Hello, number = 23
name: Hello , number: 23, num2: 11
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.