Josh Josh - 1 year ago 55
C++ Question

How do i get this function call to work properly?

I need to pass a string array to a function, have that function fill the array while counting the amount of different salsas there are in the list. There are 8. My program runs without the function call in main. With the function call I get an error for unresolved external symbol and an unresolved external. Here is my code.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

// Function Prototypes.
int getSalsaData(string, int, int);

const int max = 15;
int main()

// Declaring the Arrays.

string salsa[max];
int jars[max];
int x;
string fill = "Fill";

for (x = 0; x < max; x++)
salsa[x] = fill;
jars[x] = x;
int count = getSalsaData(salsa[max], jars[max], max);
return 0;

// The getSalsaData function.
int getSalsaData(string salsa[max], int jars[max], int max)
int a;
int total = 0;
fstream inData;"data.txt");

if (!inData.eof())
for (a = 0; a < max; a++)
inData >> salsa[a];
inData >> jars[a];
total = total + 1;
return total;

Answer Source

There are multiple problems with the shown code.

The getSalsaData function is defined thusly:

int getSalsaData(string salsa[max], int jars[max], int max)

However it's declared prototype is:

int getSalsaData(string, int, int);

If you think about it, this is obviously wrong. The last two parameters to this functions are not ints, and the first parameter is not a string. A string is just a one string. An int is just one int. But in both cases the intention is to pass an entire array or, rather, a decayed pointer to the start of the array.

A function's prototype should be exactly the same as the actual function definition, except that the parameter names are optional. So the function's prototype should be:

int getSalsaData(string [], int [], int);

However, it will be less confusing to take into account that arrays decay to pointers when they are passed as parameters. So the function should really be defined as:

int getSalsaData(string *salsa, int *jars, int max)

and prototyped as:

int getSalsaData(string *, int *, int);

The other problem is with how the function is called:

int count = getSalsaData(salsa[max], jars[max], max);

Both salsa and jars are arrays. The expression array[n] resolves to the nth element of the given array.

Here, you obviously do not intend to just pass the max-th element of both arrays (which would be a problem in of itself, since it obviously does not exist, and would be undefined behavior). Your obvious intent is to pass both arrays. To pass both arrays, just use the array's name which, as previously mentioned, will get decayed to the pointer to the start of the array:

int count = getSalsaData(salsa, jars, max);