-1

Please do not mark as duplicate, while there are similar questions to mine, they were either answered using pointers, did not address the same issue that I have, or they pertained to the language C instead of C++.

I am trying to pass an array of structs to a function, but when I try to do so, I am getting an error: declaration of ‘a’ as array of references. I think the problem may lay in the fact the compiler is reading it as an array instead of as a struct, but I am not sure how to remedy this problem.

I have defined a struct of three elements:

struct StructA {
   string name; 
   float income; 
   int amount; 
} 

Declared this struct within main:

StructA a[15]; 

And am passing it to a function like so:

void FunctionA(StructA& a[], int& count) { //& to pass by reference

}

Furthermore, right below the definition of StructA, I have the matching function prototype for the function above.

What am I doing wrong?

EDIT: Someone marked this question as a duplicate of another; it is not. I am in an intro to programming class, and as I clearly stated up top, I cannot use a pointer. Guess what the other question uses? A pointer. See the difference? Furthermore, on a more practical level, I already tried the solution recommended in Pass a dynamic array of objects to function and it did not work for me and since I cannot comment in the other question, I have to ask a new question. I will just wait until I can ask my professor, grazie.

1
  • Is it a must to have to have an array? If not try declaring a std::vector<T> of StructA and pass a std::vector<StructA>& container to your function. Commented May 11, 2017 at 2:03

2 Answers 2

1

To pass an array of any size by reference, you can do:

template <size_t Size>
void FunctionA(StructA (&a)[Size])

It'll deduce the size of the array, so you don't need to specify it each time.

StructA a1[10];
StructA a2[15];

FunctionA(a1);
FunctionA(a2);
Sign up to request clarification or add additional context in comments.

Comments

1

Use this syntax:

void FunctionA(StructA (&a) [SIZE], int &count)

SIZE should be mentioned in this case.

Your syntax (void FunctionA(StructA &a [SIZE])) means that you pass array of references(&) not a reference to an array.

You can also use a template with the function:

template <size_t Size>
void FunctionA(StructA (&a) [SIZE])

You do not need to pass count if you mean it to be size of the array as noted by:Amadeus

Using template will enable the function for different sizes as answered by: James Root

You can use the function then as follows:

StructA a[10];
StructA b[20];

FunctionA(a);
FunctionA(b);

2 Comments

Used your method but I am getting a new error: parameter ‘a’ includes reference to array of unknown bound
@Matt: you should use SIZE. I edit the answer and make it more detailed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.