0

can i pass a multi-dimension array without passing its size using pointers?

#include <iostream>
using namespace std;


void PrintArray( int(*pInt)[3] )
{
    // how to iterate here printing pInt content?

    int nRow = sizeof(*pInt) / sizeof(int);
    cout << nRow << endl; // the result: 3 not 2! i get the nColumns instead!!?
}

int main()
{
    int array[2][3] = { {1,2,3},
                        {4,5,6}};
    int(*pArray)[3] = array;
    PrintArray(pArray);

    return 0;
}
  • can anyone add the correct definition of PrintArray to print its elements
  • is there a way to pass arrays as a pointer and without passing the size?
  • thank you for throwing a glance

1 Answers1

2

can anyone add the correct definition of PrintArray to print its elements

Impossible. When the function takes the array, all that is really passed is a pointer to its first element. That's how arrays work.

is there a way to pass arrays as a pointer and without passing the size?

Arrays are always passed as a pointer to the first element, unless you pass by reference. If you only have a pointer to the first element, then you need the additional size information somehow, somewhere. If you pass by reference, then you already have the size information, because it's part of the (complete) type.

You should probably just use std::vector, anyway. Raw arrays don't behave "normally" in many ways, std::vector does.

Christian Hackl
  • 27,051
  • 3
  • 32
  • 62