Can someone explain more clearly about passing by pointer?

Hi,

I have read several web pages about passing values using pointer. But I do not get to clear grasp of how to do this.

The following code is a template I think I can pass arrays from function to the main. Is this tamplate correct?

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
#include <iostream>

//and some other libraries

using namespace std;


int function(string* S, int* I, double* D, string A);

int main()
{
	string A[10];

	//filling out the array 'A'

	int size  = 10;
	string* S = new string[size];
	int* I = new int[size];
	double* D = new double[size];

	function(S, I, D, A);

	for(int i = 0; i < size)
	{
		cout << S[i] << I[i] << D[i] << endl;
	}

	return 0;
}



int function(string* S, int* I, double* D, string A[])
{
	int size = 10;
	S = new string[size];
	I = new int[size];
	D = new double[size];

	//function computations: basically using the input string array 'A' to
	//get arrays 'S', 'I', 'D'

	return 0;
}
No, it's not correct.
You're using new[] instead of std::vector, the types for the parameter A in function mismatch, for is incomplete and you have a memory leak inside function, not to mention that there's no point passing all these parameters if you're not even using them anyway.

Perhaps you should explain what you're trying to do.
Last edited on
S, I and D are already allocated in main. You're passing that pointer to your function.

This means the function HAS a pointer to the allocated buffer. You dont' need to allocate it again.

Here's a more simplistic examlpe:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void func(int*);

int main()
{
  int* foo = new int[3];
  foo[0] = 0;
  foo[1] = 1;
  foo[2] = 2;

  func(foo);

  cout << foo[0];  // prints '3', not '0' (see func() below)

  delete[] foo;
}

void func(int* ptr)
{
  // ptr already points to something.  We don't need to allocate memory here
  ptr[0] = 3;  // because 'ptr' points to the same thing 'foo' points to, this changes the same memory
}
Hi Athar,

Then should I use vector<string> S?

The functiuon function will establish arrays (S, I, D) that will be used in the main and the other functions that the main will call.

I wonder if I dont pass S, I, D arrays, can the main still access the values in S, D, I?


The pointer concept is really confusing to me.
Would you be kind to just write a brief template for passing mutiple arrays from the function to the main?

Thanks
Thanks Disch,

Now I get it.
Topic archived. No new replies allowed.