Array of pointers as a function parameter

I have a basic question about array and pointer in C / C ++.

Say I have:

Foo* fooPtrArray[4];

How to pass fooPtrArrayto a function? I tried:

int getResult(Foo** fooPtrArray){}  //  failed
int getResult(Foo* fooPtrArray[]){} // failed

How can I handle an array of pointers?

EDIT: I once thought the error message was related to passing the wrong array of pointers, but from all the answers, I understand that this is something else ... (pointer assignment)

Error msg:
Description Resource Path Location Type incompatible types in assignment of 
`Foo**' to `Foo*[4]' tryPointers.cpp tryPointers line 21 C/C++ Problem

I don’t quite understand why he says: Foo * * to Foo * [4]. If as a function parameter they mutually change with each other, why does this give me a compilation error during assignment?

I tried to duplicate the error message with minimal code as follows:

#include <iostream>

using namespace std;

struct Foo
{
int id;
};

void getResult(Foo** fooPtrArray)
{
cout << "I am in getResult" << endl;
Foo* fooPtrArray1[4];
fooPtrArray1 = fooPtrArray;
}

int main()
{
Foo* fooPtrArray[4];
getResult(fooPtrArray);
}
+3
5

int getResult(Foo** fooPtrArray)

int getResult(Foo* fooPtrArray[])

int getResult(Foo* fooPtrArray[4])

( ).

, . " "?

, , , , , ,

int getResult(Foo* fooPtrArray[], unsigned n);
...
Foo* array3[3];
Foo* array5[5];
getResult(array3, 3);
getResult(array5, 5);

4 ,

int getResult(Foo* (*fooPtrArray)[4])

Foo* array[4];
getResult(&array);

( &, ).

, , ++,

int getResult(Foo* (&fooPtrArray)[4]);
...
Foo* array[4];
getResult(array);
+10

:

Foo* fooPtrArray[4];

Foo ( , Foo*).

C/++ . , "" , .

fooPtrArray " " , , .

, , . , , . :

int getResult(Foo** fooPtrArray, int arraySize);

Foo ( Foo) :

for (int i=0; i < arraySize; i++)
{
    Foo* fooPtr = fooPtrArray[i];
    if (fooPtr)
    {
        fooPtr->memberFunction();
        fooPtr->memberVariable;
    }
}
+2

, . - :

int returnValue;
returnValue = getResult(fooPtrArray);
0

, int?!

@Kinopiko your code does not compile in C ++.

@Lily, what error message do you get? in your example, getResult should return an int. This is probably not the case.

0
source

Source: https://habr.com/ru/post/1722636/


All Articles