5 years, 10 months ago.

How to pass an array of objects as a function parameter

Hello guys!

I know C and now I am learning C++. I am also trying to learn ehow to organize my code and some good programing practices.

I am making a project to my internship and ended up in a very confusing situation.

What I need it to pass an array of objects as a function parameter. How do I do that?

I found that I could use a vector, but this concept is also new to me, is there a diferent way to do it?

1 Answer

5 years, 10 months ago.

In c (and c++) all an array variable really is is a pointer to a block of memory. If you pass that to a function then the size of the array is lost, to get around that problem the normal trick is to pass two parameters, the array and the size of the array.

Because the compiler treats arrays an pointers as interchangeable there is no need to explicitly cast between the two e.g.

// sets all the values in an array to 0
void clearArray(int myIntArray[], int arraySize) {
  for (int i = 0; i<arraySize; i++) 
    myIntArray[i] = 0;
}

// sets all the values in an array to 1
void setArray(int *intPtr, int arraySize) {
  for (int i = 0; i<arraySize; i++) 
    *(intPtr+i) = 1;    
}
// c note for newbies:
// The amount the pointer increases when you add something to it will depend on the size of the data type it points to.
// intPtr+1 is automatically taken as being intPtr + 1*sizeof(int) rather than increase by a value of 1.

main () {
  int myArray[10];
  clearArray(myArray,10);
  setArray(myArray,10);
}

This would still work if the array is of a user defined structure or object. However if you are using a non-standard data type then what would be a lot more common is to have an array of pointers to the objects rather than an array of the objects themselves. That way if you need to re-order the array or pass a single element of the array to a function then all you need to move around are pointers rather than all of the memory needed for that object. That can save a lot of CPU time shuffling memory contents around.

std::vector is a very useful c++ tool, it gives you an array type structure that you can grow and shrink as needed. Since the vector keeps track of how many items it contains you don't have to pass the size as a second parameter. However the convenience comes with a cost, because it is allocating and freeing memory as needed it also takes up more memory for the same number of data points and is a lot slower than an array. For embedded code on something as slow and short of memory as an mbed I'd say to use an array unless you really really need the extra features a vector can give you.

Accepted Answer

Thanks for the answer Andy! You told me everything I was looking for and a little more.

posted by Thiago . 04 Sep 2015