What Does a Double Pointer Point To in C/C++?

0
3
Asked By CuriousCoder42 On

I'm trying to understand how double pointers work in C/C++. Specifically, I'm using a double pointer to point to an array of structures. My definition looks like this: `my_struct** ptr;`. I'm curious if this means that `ptr` is pointing to an array of pointers, each pointing to individual elements of the structure, or if it just creates a single pointer that points to the entire array. It seems to me like I should just need a single pointer to access my structure's array directly, rather than having multiple pointers for each element. How does this all work, and what's the best way to approach this? Any insights or examples would be appreciated. Thanks!

2 Answers

Answered By CodeNinja88 On

In C/C++, when you declare a double pointer, keep in mind that arrays automatically convert to pointers when used. So, for example, if you have `int a[] = {1, 2, 3}`, the array name `a` is treated as a pointer to its first element. When you define a double pointer like `int **pp`, it points to a pointer (which can point to the first element of your array), rather than creating an array of pointers. It's more about how you manage memory with those types.

MemoryMaster -

Just to clarify, for `int **pp = &a;`, `a` is an array, and you can't take the address of an implicit pointer like that since it doesn't have a distinct address. So, `pp` in this case might not work as expected. It's important to remember type conversions when dealing with pointers.

Answered By TechieTom On

A double pointer (`my_struct** ptr`) is indeed a pointer to a pointer. If you're just trying to access a continuous block of memory for your structures, a single pointer (`my_struct* ptr`) is usually sufficient. You'd typically use a double pointer if you're passing your pointer into a function that needs to allocate memory and return it to the caller. This way, the first pointer points to the address of the second pointer, holding the actual memory region.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.