Passing Array as a parameter of a function

1

How to pass a array to a function without having to report how many indexes it has?

Reporting the size

#include "stdafx.h"
#include <Windows.h>

void imprimir(int _array[], int _tamanho) {
    for (int i = 0; i < _tamanho; i++) {
        printf("%d\n", _array[i]);
    }
}

int main()
{
    int myArray[] = { 1, 2, 3, 4, 5 };
    imprimir(myArray, 5);

    getchar();
    return 0;
}

Without the size

#include "stdafx.h"
#include <Windows.h>

void imprimir(int _array[]) {
    // Aqui ele deve ser capaz de descobrir sozinho o tamanho da array.
    int tamanho = _array[].tamanho; // Apenas uma abstração.

    for (int i = 0; i < tamanho ; i++) {
        printf("%d\n", _array[i]);
    }
}

int main()
{
    int myArray[] = { 1, 2, 3, 4, 5 };
    imprimir(myArray);

    getchar();
    return 0;
}

I would like to give intelligence to my program so that it is able to figure out the size of the array by itself without having to pass it as a parameter.

    
asked by anonymous 05.08.2018 / 10:11

1 answer

4

If you are using C ++, use the language features and adopt the vector which is an essentially costless abstraction, correct in this language, it has many advantages. Do not program in C when you are using C ++.

#include <iostream>
#include <vector>
using namespace std;

void imprimir(vector<int> &array) {
    for (int item : array) cout << item << ' ';
}

int main() {
    vector<int> myArray = { 1, 2, 3, 4, 5 };
    imprimir(myArray);
}

But if you want to do the C-way, then go over the size always. Or create an abstraction for it to go together, but it will recreate vector only a way worse. Or use a global constant with size, since in this case you know and use within your function, but this is easy to make a mistake, none of that makes up for it. Just do not use a number as a terminator, unless it's exactly what you need.

    
05.08.2018 / 16:29