1

I am trying to print the x value for newBall, but don't understand how to access it. Can someone help me out? I have a pointer to a struct Ball within the struct AllBalls. I get a compile error saying x is not a member of a structure.

    #include <stdlib.h>
    #include <stdio.h>


    struct Ball {
        char id;
        double x;
        double y;
        double Vx;
        double Vy;
    };

    struct AllBalls {
        int count; 
        struct Ball *ballPtr; 
    };

int main(void) 
{   
    int index = 1; 
    struct AllBalls list = {0, NULL};
    struct Ball newBall;
    double x, y, Vx, Vy;
    int input;

    printf("Enter input: ");
    input = scanf("%lf %lf %lf %lf", &x, &y, &Vx, &Vy);
    list.count++;
    list.ballPtr = &newBall;
    newBall.id = 64 + list.count;
    newBall.x = x;
    newBall.y = y;
    newBall.Vx = Vx;
    newBall.Vy = Vy;
    printf("%lf", *(list.ballPtr).x);
}   

1 Answer 1

3

The problem is in this line near the end:

 printf("%lf", *(list.ballPtr).x);

The member selection operator . has higher precedence than the dereference operator *. So the compiler thinks you're trying to access a pointer as a struct. You can fix this by moving the parenthesis:

 printf("%lf", (*list.ballPtr).x);

Or by using the pointer to member operator -> instead:

 printf("%lf", list.ballPtr->x);
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.