I'm trying to understand how double pointers function when dealing with arrays in C. Specifically, I have a double pointer, `my_struct** ptr`, and I want it to point to an array of `my_struct`. However, it seems like a double pointer creates multiple pointers, each pointing to an element of the array instead of just one pointer to the array itself.
I want to simply go to the location that a single pointer points to and then index into my array of structures. It feels unnecessary to have multiple pointers for each element.
Can anyone clarify how double pointers actually work in this context? Thanks!
3 Answers
Remember, creating a pointer doesn't allocate memory. You need to use functions like `malloc()` to actually get memory allocated, whether you use a single or a double pointer. The size of pointers is consistent in modern systems (usually 64 bits), but they point to their own types. If you’re working with data structures, make sure you allocate memory correctly.
A double pointer is essentially a pointer to another pointer. If you just need a pointer to a continuous block of memory holding your structures, a single pointer will do the trick. Double pointers are usually used in scenarios like allocating memory in a function and passing that pointer back to the caller, where the double pointer will hold the address of this memory region. If you're simply indexing into an array, a single pointer is typically all you need.
In C/C++, an array decays into a pointer to its first element, which means if you have an array like `int a[] = {1, 2, 3, 4, 5}`, you can treat it as a pointer `int *p = a`. A double pointer, like `int **pp`, points to this pointer, not to an array of pointers. So, it does not create a separate pointer for each element; instead, it simply gives you a way to track the first pointer that leads you to the array.
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