Letting 2 pointer pointing to same address

2301 views c
-4

I have just started learning data structure and i was confused by pointer.

typedef struct{
    int* id;
}book;

I have created two book variables by malloc()

book* A;
A=(book*) malloc(sizeof(book)*2)
int bookid = 1234;

How can I make A[0].id and A[1].id pointing to book id to achieve that when I change one of it, another will change as well?

answered question

Why do you want a pointer to the id? That just makes no sense to me. Better make the id member a non-pointer.

@Someprogrammerdude I think just for the sake of an example.

Messing up with pointers is really dangerous. Why shouldn't you use just "references" instead?

1 Answer

10

You do

A[0].id = &bookid;

and

A[1].id = &bookid;

& sign gets the address of the variable.

posted this

Have an answer?

JD

Please login first before posting an answer.