Why two pointers??

My professor gave us a program to look at but not sure why there are two pointers in the argument can someone help me??

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
36
37
38
39
40
41
42
43
44
45
46
  #include <iostream>
#include <cstring>
using namespace std;
const int MAX = 3;
void assignNames(char **);

 

int main()

{
char* names[MAX];
assignNames(names);
for (int count = 0; count < MAX; count++)
   cout <<"Name " << count + 1 << " is " << names [count] << "\n";

for (int count = 0; count < MAX; count++)

   delete names [count];
return 0;

}

 

void assignNames(char** param)

{

for (int count = 0; count < MAX; count++)

{

   char buffer[80];

   cout << "Enter name: ";

   cin >> buffer;

   param [count] = new char [strlen(buffer) + 1];

   strcpy(param[count], buffer);

}

}
There is a slight twist to the pointer-to-pointer answer...

When you have an array of a given type and you pass it to a function, what is passed to the function is actually a pointer to the first element. So an int array (of any size) turns up at the function as an int* to the first element. This is known as array decay.

what is array decaying?
http://stackoverflow.com/questions/1461432/what-is-array-decaying

And it's how and why this works.

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
#include <iostream>
#include <string>
using namespace std;

const int MAX = 3;

// C++ also allows you to use [] instead. But if you uncomment this
// "overload" of test you'll find that the compiler thinks it's the same
// as the following one so hitting the one definition rule.
//
// (In fact, you can put a number in the [] -- BUT IT'S IGNORED!)
//
//void test(int arr[])
//{
//  for (int index = 0; index < MAX; ++index)
//    cout << "arr[" << index << "] = " << arr[index] << "\n";
//}

void test(int* arr)
{
  for (int index = 0; index < MAX; ++index)
    cout << "arr[" << index << "] = " << arr[index] << "\n";
}

int main ()
{
  int arr[MAX] = {1, 2, 3};
  test(arr);
  return 0;
}


As your array is an array of char*s, what turns up at the function is a pointer to a char*, otherwise known as a char**.

Which gets us back to rlc4's response.

Andy

PS Your code is rather scruffy!! :-(
Last edited on
ah i get it now thanks you guys and yea sorry about that andywestken just our professor are giving us examples of stuff like this and we have to look at them and figure whats going on
Topic archived. No new replies allowed.