Hello guys, totally new to programming so pardon me if this is a really dumb topic to ask! I understand basic pointer theories, but I can't seem to wrap my head around pointer to an array of character pointers.
Like:
1 2
|
typedef char * word;
word *w [5];
|
I know that in essence is doing:
but that's about all I understand.
I found an example online that can help with making my questions clearer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
#include <iostream>
using namespace std;
void func(char **& ref_to_ptr); /* Function declaration */
int main(void)
{
/* Declare the '2D Array' */
char ** ptr = new char * [5];
ptr[3] = new char[20];
/* Put some data in the array */
ptr[3] = "k";
/* Print the first value on the screen */
cout << "First value: " << ptr[3] << endl;
/* Pass the array by reference to the function 'func()' */
func(ptr);
/* Again we print on the screen what's in the '2D Array' */
cout << "Second value: " << ptr[3] << endl;
/* Wait for the user to press ENTER */
cin.get();
/* Cleanup */
delete[] ptr;
/* Tell the Operating System that everything went well */
return 0;
}
void func(char **& ref_to_ptr)
{
/* This function demonstrates how to change the value of it's argument(s) */
ref_to_ptr[3] = "tux4life";
}
|
My questions:
1) What actually happens in this line?
char ** ptr = new char * [5];
Is it declaring that ptr is a pointer to a char pointer and thereafter allocating an array of 5 char pointers? So essentially, ptr is pointing to the first element of the array of 5 char pointers? Not sure if I'm making any sense?! o.O
2) Also, if the above is true, then am I right to say that I can treat ptr[1] like a character array by itself? So if I
cout << ptr [1];
I would get the string that is pointed to by ptr [1]?
Then the next question would be, how do I access the individual character in that string pointed to by ptr [1]?
3) So if i
cout << *(ptr + 1);
Am I displaying ptr[1] also, since ptr is pointing at ptr[0]?
4) Why is there a need for a * after the new char? Why can't I just do
char ** ptr = new char [5];
5) How do we pass pointers and pointers to pointers and pointers to arrays into a function? For pointers to arrays, isn't array passed by reference by default? Why is the example code using the ampersand (&) to pass the 2D array?
6)
1 2
|
char **w [5] //declaring an array of 5 pointers to char pointers
char **w = new char * [5] // declaring a pointer to an array of 5 character pointers
|
Is that correct?