简体   繁体   中英

assigning pointer to another pointer, does the second pointer point to the same address as the first one?

in C programming, I am wondering about the following pointer assignment:

struct transaction_t {
  int id;
  char *name;
};

typedef struct transaction_t* transaction;

transaction pointer1 = malloc(sizeof(struct transaction_t));
transaction pointer2 = pointer1; /* is this a valid assignment? */

My question is: does the pointer2 point to the same address as pointer1 points to? can I perform the following using pointer2?

pointer2->name = "Chase Bank"
pointer2->id = 100;

For assining pointer1 to pointer2, should I malloc memory for pointer2 first?

After the assignment they both point to the same place.

Imagine you and your friend are in a room someone brings an empty box into the room and you point at it. You are now pointing at allocated memory. If your friend points at it too then you are both pointing at the same locations.

Assignments to either will put it in the same box.

You can also overwrite what is in the box.


It really does help to think of entities pointing and boxes when thinking about pointers in C and how they work. I'd have never been able to write my first linked list without boxes and arrows drawn on a page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM