I'm trying to understand how pointers work in C, specifically when using malloc. I declared two pointers like this:
`struct cplx *p1 = malloc(sizeof(struct cplx));`
`struct cplx *p2 = malloc(sizeof(struct cplx));`
My question is, do p1 and p2 point to the same address, meaning they can modify each other's values, or do they point to separate copies of the struct cplx? Thanks, and I'd appreciate short replies!
3 Answers
Actually, if you call `malloc()` multiple times, you get separate allocations. One address won't necessarily be reused in the next call unless you free the memory first, then it's possible, but not guaranteed. Each `malloc()` typically allocates a distinct block.
When you call `malloc()`, it allocates unique memory for each pointer. So, p1 and p2 will point to different memory addresses, meaning they can modify their own values independently without affecting each other.
Just to clarify, in this example:
`struct cplx *p1 = malloc(sizeof(struct cplx));`
`free(p1);`
`struct cplx *p2 = malloc(sizeof(struct cplx));`
In this case, p1 and p2 could indeed point to the same memory location after p1 is freed, but that behavior is not guaranteed. It's best practice to consider every `malloc()` call as giving you a unique block of memory.
Related Questions
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically