1

function find_young() have to receive pointer p as an actual parameter. And p have to point a struct s which has youngest person. There is no error message but the program isn't work. Please give me some advice.

typedef struct
{
    char *name;
    int age;
} PERSON;

void find_young(PERSON **ip)
{
    PERSON s[3] = {{"John", 25}, {"Brandon", 28}, {"Alex", 30}};
    int i;
    int min = s[0].age; 
    for(i = 0; i < 3; i++)
    {
        if(min > s[i].age)
            **ip = s[i];
    }
}

int main()
{
    PERSON *p;
    find_young(&p);
    printf("The youngest person is %s.\n", p->name);
}
8
  • a advice PERSON *p; --> PERSON p; also s[0] is not set when the minimum. Commented Nov 30, 2015 at 7:52
  • can you explain that more easily? Commented Nov 30, 2015 at 8:02
  • Concrete fix example Commented Nov 30, 2015 at 8:05
  • What I should do if I have to use double pointer? Commented Nov 30, 2015 at 8:09
  • Your pointer has not been set should pointer point to the Object(PERSON Object). E.g PERSON aMan; PERSON *p = &aMan; Commented Nov 30, 2015 at 8:11

2 Answers 2

2

You need to make a number of changes in your code to make it work


1) You need to allocate memory to the struct, and for the char* name in the struct

int main()
{
    PERSON *p = malloc(sizeof(PERSON));
    p->name = malloc(100);
    find_young(&p);
    printf("The youngest person is %s with age %d.\n", p->name, p->age);

    free(p->name);
    free(p);
}


2) Then you need to copy both the name and age values to the passed struct properly

void find_young(PERSON **ip)
{
    PERSON s[3] = {{"John", 25}, {"Brandon", 28}, {"Alex", 30}};
    int i;

    int min = s[0].age;             //copying the first value
    (**ip).age = s[0].age;
    strcpy((**ip).name, s[0].name);

    for(i = 1; i < 3; i++)          //starting from the next values to compare
    {
        if(min > s[i].age)
        {
            (**ip).age = s[i].age;
            strcpy((**ip).name, s[i].name);
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Mind you its best practice to include free() statements after the printf in the main() function. Otherwise if the program doesn't terminate after that you have a memory leak.
@Magisch, I always miss that. :)
0

In your code,

  • either, for p, before passing &p to the function
  • or, for *ip, inside the function

you need to allocate memory. Other wise, you'll end up dereferencing invalid pointer, which invokes undefined behavior.

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.