1

I came across this code:

typedef struct {
    char *name;
    char *value;
} SPAM;

typedef struct {
    char *name;
    int num_spams;
    SPAM *spams;
} EGG;

SPAM my_spams[2] = {
    { "name1", "value1" },
    { "name2", "value2" },
};

EGG my_eggs[1] = {
    { "first egg", 1, my_spams }
};

EXPORT(int) getSPAMANDEGGS(EGG **eggs)
{
    *eggs = my_eggs;
    return 1;
}

In this declaration shouldn't the definition of EGG struct have SPAM **spams; as the definition of the spams member since we store an array of SPAMs there later?

3
  • 2
    Arrays decay to pointers. So SPAM *spams can point to the first element of an array of SPAM. Commented May 10, 2018 at 0:42
  • 1
    Just like you can write char foo[] = "abc"; char *foo_ptr = foo; Commented May 10, 2018 at 0:43
  • { "first egg", 1, my_spams } should be { "first egg", 2, my_spams }, because num_spams should correspond to the number of elements in my_spams array, which is 2. Commented May 10, 2018 at 0:48

1 Answer 1

1

No, it should not. An array of SPAM values is expressed through a single pointer, so SPAM *spams is correct.

The reason the parameter of the getSPAMANDEGGS function needs two asterisks is that it sets a pointer passed to it from the outside:

EGG *eggArray; // First asterisk is due to *
int eggArraySize = getSPAMANDEGGS(&eggArray); // Second asterisk is due to &

Without the & operator getSPAMANDEGGS would be unable to set a new value to eggArray pointer.

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.