윤성필
윤성필

Reputation: 85

control double pointer on array of structs

I need to print a name for pointer. But it doesn't works at all. Console stops..

Maybe the problem will be on 'find_young' function. I don't know what's the problem and how to fix it. What can I do for a right code.

Below are my codes.

========

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

PERSON s[3] = { {"ACE", 25}, {"HEART" ,28}, {"CLOVER", 40} };

void find_young(PERSON **p) {
    int i;

    for (i = 0; i < 1; i++) {
        if (s[i].age > s[i+1].age) {
            p = &s[i+1];
        }
    }
};

void Ex1()
{   
    struct PERSON *p;
    p = &s[0];

    find_young(&p);
    printf("youngest man is %s.", p->name);
}

Upvotes: 1

Views: 1015

Answers (2)

Punit Vara
Punit Vara

Reputation: 4194

struct PERSON is wrong , you have already used typedef so no need to use struct . Just use PERSON *p. To find the youngest , you code should be as follow:

#include<stdio.h>
typedef struct {
        char *name;
        int age; 
    } PERSON;

    PERSON s[3] = { {"ACE", 100}, {"HEART" ,28}, {"CLOVER", 40} };

    void find_young(PERSON **p) {
        int i;
       for (i = 0; i < ((sizeof(s)/sizeof(s[0]) -1); i++) { 
            if (*(p)->age > s[i+1].age) { 
                  *p = &s[i+1]; 
            } 
       } 

    };

    void Ex1()
    {   
        PERSON *p;
        p = s;

        find_young(&p);
        printf("youngest man is %s.", p->name);
    }
int main()
{
Ex1();
return 0;
}

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409176

You are assigning between wrong types, and the compiler should warn you about it:

p = &s[i + 1];

Here the expression &s[i + 1] is a pointer to PERSON, but p is a pointer to a pointer to PERSON. Not quite the same thing.

What you want is

*p = &s[i + 1];

Upvotes: 6

Related Questions