cdahms
cdahms

Reputation: 3750

C++ - how to pass an array into a function that takes an int * type, within a function

I usually use vectors in C++, but in a particular case I have to use arrays which I'm not used to. If I do this:

// GetArraySize.cpp

#include <iostream>

#include <conio.h>   // remove this line if not using Windows

int main(void)
{
  int myArray[] = { 53, 87, 34, 83, 95, 28, 46 };

  auto arraySize = std::end(myArray) - std::begin(myArray);

  std::cout << "arraySize = " << arraySize << "\n\n";

  _getch();    // remove this line if not using Windows

  return(0);
}

This works as expected (arraySize prints out as 7). But if I do this:

// GetArraySizeWithFunc.cpp

#include <iostream>

#include <conio.h>    // remove this line if not using Windows

// function prototypes
int getArraySize(int intArray[]);

int main(void)
{
  int myArray[] = { 53, 87, 34, 83, 95, 28, 46 };

  int arraySize = getArraySize(myArray);

  std::cout << "arraySize = " << arraySize << "\n\n";

  _getch();    // remove this line if not using Windows

  return(0);
}

int getArraySize(int intArray[])
{
  auto arraySize = std::end(intArray) - std::begin(intArray);

  return((int)arraySize);
}

On the line auto arraySize = std::end(intArray) - std::begin(intArray); I get the error:

no instance of overloaded function "std::end" matches the argument list, argument types are: (int *)

What am I doing wrong?

I should mention a few things:

-I'm aware that with C++ 17 I could use std::size(myArray), but in the context I'm working in I can't use C++ 17

-There may be other / better ways to write a getArraySize() function, but moreover I'm trying to better understand how old-style arrays are passed into / out of functions

Upvotes: 0

Views: 74

Answers (1)

Fureeish
Fureeish

Reputation: 13424

Implement std::size yourself:

template <typename T, std::size_t N>
constexpr auto size(const T(&)[N]) {
    return N;
}

usage:

int main() {
    int arr[] = {1, 2, 3};

    std::cout << "size: " << size(arr);
}

Note that you need to pass a reference to the array, since simply passing T[] will actually make you pass a T* to the first element of the array. That will not preserve any infromation regarding the array's size.

Upvotes: 2

Related Questions