Passing Object Arrays Between Functions

Hi,
I can't figure out how to pass arrays between functions, in particular as to how to get an array to return.

For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;

int pass(int num[])
{
   return num;
}

int main()
{
  int num[10];
  num = pass(num);
  return 0;
}

This doesn't work. What do I need to do to pass an entire array between functions?
Last edited on
Hi zimbloggy,

Please edit your post and put the source inside code tags. It will make your post a lot more legible and folks here will be more likely to look at it.

Also, in the future, these sorts of questions are best asked in the Beginner forum.

Sorry about that, I am pretty new to this forum.
You need to define "doesn't work". Does it give you an error? Does it compile, but do something different? Does it compile and crash?
It doesn't compile. In "return num" the num is red-underlined. It says:

int *num
error: return value type does not meet the function type


and in the num = pass(num), it has the first num red-underlined, saying:

int num[10]
Error: expression must be a modifiable l-value
Last edited on
You cannot return arrays from functions.

Instead, you pass the array "by pointer" or "by reference" to the function, and the function modifies it.

This is how functions like strcpy, etc work.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void pass(int* num)
{
  num[0] = 3;
  num[1] = 1;
  num[2] = 4;
}

int main()
{
  int num[10] = {0};
  pass(num);  // modifies num

  cout << num[0];  // prints '3'
  cout << num[1];  // prints '1'
  cout << num[2];  // prints '4'
}
Thanks! It's interesting how it is set up that way.
Topic archived. No new replies allowed.