I'm having trouble understanding why passing my array, containing elements, to a function, results in my array no longer containing elements within the function.
Before passing in an array containing 3 objects from my items sturct, the size of the array is 72 (24 for each object). Once inside the function, the size of my array is 24, which I assumed to be the size of the first element in my array. However, this is not the case.
My question, why isn't my array the same in the function as it is outside of the function?
Header File:
#include <iostream>
using namespace std;
// header file for shop items
struct items
{
string name;
int price;
string examine;
};
main file:
#include "shop_items.h"
#include <iostream>
using namespace std;
int getLongestName(items &shop)
{
/*Iterates over each element in array
if int longest < length of element's name, longest = length of element's name.*/
int longest = 0;
// shop size is 24, the size of a single element.
cout << "sizeof(shop) right inside of function:" << sizeof(shop) << endl;
return longest;
}
void test1()
{
// initialize shop items
items sword;
items bow;
items shield;
// set the name, price, and examine variables for each item.
sword.name = "sword"; sword.price = 200; sword.examine = "A sharp blade.";
bow.name = "bow"; bow.price = 50; bow.examine = "A sturdy bow.";
shield.name = "sheild"; shield.price = 100; shield.examine = "A hefty shield.";
// create an array for iterating over the each element in item shop.
items shop[] = {sword, bow, shield};
//sizeOfShop = 72, 24 for each element (the sword, bow and shield).
cout << "sizeof(shop) right outside function: " << sizeof(shop) << endl;
int longest = getLongestName(*shop);
}
int main()
{
test1();
cout << "\n\nPress the enter key to exit." << endl;
cin.get();
}
What is useful about a reference-to-array parameter?
The answer to the above question has helped me a lot at better understanding what it is that I'm trying to do. However, I'm running into different errors when attempting to pass my array by reference as well.