k9b
k9b

Reputation: 1493

Pointer arithmetic with structs

Couple questions along these lines, but I dont quite understand any of them.

struct bundle 
{
    int x;
    int y;
};

void foo(struct bundle *A, int p)
{
    A->x = p;
    A->y = p;
}

main()
{
    struct bundle ptr;
    foo(&ptr, 0);
    //printf("%d",*(ptr + 1)); ISSUE HERE
}

My print statement is not working... Any ideas?

I'm using an online C compiler which is giving me this error

invalid operands to binary +

but I dont think that the compiler has anything to do with it.

I've tried casting it to an (int *) but no luck. I am pretty sure I am doing the correct *(ptr + 1) and I dont have to do *(ptr + sizeof(int)) or anything like that.

Thanks for the help!

Upvotes: 0

Views: 226

Answers (1)

user1804599
user1804599

Reputation:

ptr is not a pointer. It's a struct bundle. You have to take the address with &:

printf("%d", *(&ptr + 1));

This will of course result in undefined behaviour, but it's well-formed.

Did you mean printf("%d", ptr.y); or printf("%d", ptr.x + 1);?

Upvotes: 2

Related Questions