Passing array as a function parameter

Asked

Viewed 861 times

1

How to pass a array to a function without me having to inform the amount of indexes it has?

Stating 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 my program intelligence so that it will be able to figure out the size of the array without having to pass it as a parameter.

1 answer

4


If you are using C++ use the language resources and adopt the vector which is an abstraction, essentially without cost, correct in this language, it has numerous advantages. Do not program in C when 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);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

But if you want to do it the C way then always pass the size. Or create yourself an abstraction that will go along, but will recreate the vector only in a far worse way. Or use a global constant with the size, since in this case you know and use within your function, but this is easy to make a mistake, none of this pays off. Just don’t use a number as a terminator, unless it’s exactly what you need.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.