0

Considering I have the following array:

int * a = new int[1000];

I would like to pass this array to a function by reference. If I would be calling this function from main:

int main()
{
    int * a = new int[1000];
    func(a);
    //print the elements of the array
    for(int i=1;i<=sizeof(a);i++) cout<<a[i]<<" ";
    return 0;
}

My function would be:

void func( ??? )
{
//write some elements in the array
for(int i=1;i<=sizeof(a);i++) a[i]=i;
}

How do I have to declare func?

Shury
  • 468
  • 3
  • 15
  • 49
  • Possible duplicate of [General rules of passing/returning reference of array (not pointer) to/from a function?](http://stackoverflow.com/questions/5398930/general-rules-of-passing-returning-reference-of-array-not-pointer-to-from-a-fu) – Nasser Al-Shawwa Feb 24 '16 at 01:16
  • 3
    You do not have an array. You have a pointer. You will have to pass a size with it to the function. – NathanOliver Feb 24 '16 at 01:17
  • 1
    Why not use `std::vector`? – Ed Heal Feb 24 '16 at 01:27

3 Answers3

3

Well the primary flaw is that sizeof(a) doesn't do what you think it does, if int * a; is passed to your function. It just calculates the size of the pointer variable itself at compile time. There's no information kept with the pointer that it was allocated using new int[1000]; and the size was 1000.

You need to pass the array size explicitly with an additional parameter, or better use std::vector<int> a(1000); at all.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
1

You cannot just pass a, It should be,

func(a,1000);

Your function will be,

void func( ??? ) --> `void func( int *a, size_t size)

Pranit Kothari
  • 9,721
  • 10
  • 61
  • 137
1

The idea is to accept an array of integers of a certain size.

void func(int (&arr)[1000]) {
  // insert logic here
}

The above will only accept int arrays of size 1000 - no more, no less.

You are not passing an array, though. You're passing a pointer, so you need to pass the size:

void func(int *arr, size_t n) {
  // insert logic here
} 
erip
  • 16,374
  • 11
  • 66
  • 121