Am I using array pointers in functions correctly here?

Hi, I'm relatively new to C++ and trying to write a program to aid in a physics project. I'm a little unsure of my understanding of how arrays are used in functions - I get that functions can't return an array but rather a pointer to it - so I wrote the following short program to see if I'm getting it right.

The program creates 3 small arrays, A, B and C. Function_1 fills arrays A and B based on an integer k=5, and function_2 performs a simple operation on arrays A and B and stores the results in array C. Main prints out the contents of all 3 arrays.

The program works fine and exactly the way I want it to but can someone please tell me if my use of arrays and pointers in the functions is correct? Or in other words, am I handling the arrays as efficiently as possible?

Thanks for any help.

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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85

#include <iostream>
using namespace std;


//Program involving 3 arrays.
//Function_1 fills the first two arrays.  Function_2 performs a simple
//operation on the first two arrays and then stores the result in the third 
//array. Main prints out the contents of all three arrays.



int main() {

int i;
int k=5;


int *array_A;
array_A = new int[5];

int *array_B;
array_B = new int[5];

int *array_C;
array_C = new int[5];

void* function_1(int k, int array_A[5], int array_B[5]);
void* function_2(int k, int array_A[5], int array_B[5], int array_C[5]);


function_1(k,array_A,array_B);			//call functions
function_2(k,array_A,array_B,array_C);


cout << endl << "array_A = ";			//print out arrays

for (i=0;i<=4;i++) {
	cout << array_A[i] << " ";
}

cout << endl << "array_B = ";

for (i=0;i<=4;i++) {
	cout << array_B[i] << " ";
}

cout << endl << "array_C = ";

for (i=0;i<=4;i++) {
	cout << array_C[i] << " ";
}



delete [] array_A;
delete [] array_B;
delete [] array_C;

return 0;
}



void* function_1(int k, int array_A[5], int array_B[5]) {

	for (int i=0;i<=4;i++) {
		array_A[i] = k+i;
	}

	for (int i=0;i<=4;i++) {
		array_B[i] = k*i;
	}

}


void* function_2(int k, int array_A[5], int array_B[5], int array_C[5]) {

	for (int i=0;i<=4;i++) {
		array_C[i] = k*(array_A[i] + array_B[i]);
	}

}



Last edited on
Looks fine except your functions are returning void* (a pointer) instead of void (nothing), which they should be.

I'm surprised your compiler isn't giving you errors because of that.
Thanks. My usual compiler does not give any errors and the program works fine but I just tried my other compiler which does give me errors, which removing the asterisk from void* corrects. I don't know why the first compiler does not produce any errors.
Topic archived. No new replies allowed.