c++按值传递结构数组

C++ pass array of struct by value

本文关键字:数组 结构 按值传递 c++      更新时间:2023-10-16

我很难理解为什么将包含元素的数组传递给函数,导致数组不再包含函数内的元素。

在传入一个包含3个对象的数组之前数组是72(每个对象24)。一旦进入函数,数组的大小是24,我假设它是数组中第一个元素的大小。然而,这事实并非如此。

我的问题,为什么我的数组在函数中不一样,因为它在函数之外?

头文件:

#include <iostream>
using namespace std;
// header file for shop items
struct items
{
    string name;
    int price;
    string examine;
};
主要文件:

#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 << "nnPress the enter key to exit." << endl;
    cin.get();
}

对数组的引用参数有什么用处?

以上问题的答案帮助我更好地理解了我正在努力做的事情。然而,当我试图通过引用传递我的数组时,我遇到了不同的错误。

没有传递数组。只传递数组的第一个元素。

int longest = getLongestName(*shop);

表达式*shop等价于shop[0],所以在函数内部你得到一个类型为items的对象的大小。

此外,您将函数getLongestName声明为具有指向类型为items的对象的引用类型的参数。

int getLongestName(items &shop);

如果你想通过引用将整个数组传递给函数,那么你应该将其声明为

int getLongestName( items ( &shop )[3] );

,函数必须以

的形式调用
int longest = getLongestName(shop);

int getLongestName(items *shop, size_t n);

第二个形参指定数组中元素的个数。

函数必须以

的形式调用
int longest = getLongestName(shop, 3 );