c++按值传递结构数组
C++ pass array of struct by value
我很难理解为什么将包含元素的数组传递给函数,导致数组不再包含函数内的元素。
在传入一个包含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 );
相关文章:
- 从函数中全局删除并重新实例化数组结构,而无需在编译时知道数组的大小
- 如何使用函数的输出初始化 const 数组结构字段?
- 传递数组结构、ofstream 和 interger 以运行
- 从文本文件中读取并输入到数组结构中,然后显示读取的数据C++
- 将文本文件读取到数组结构中
- C/C++中数组结构和数组结构的通用接口
- C++ MDC final-在字符类型的数组结构中按字母顺序对记录中的名称进行排序
- C++ 使用数组结构创建平衡的二叉搜索树
- C++:释放动态数组(结构成员)和指向此结构的指针的方法
- 使用 vector 在 c++ 中声明 3D 数组结构
- 数组结构无法正确打印
- 如何在C++中访问数组结构内部的数组结构
- CIN进入数组结构似乎什么也没输入
- ifstream将数组结构到txt文件中,然后尽可能将其提取为数组
- wlanapi-将WlanFreeMemory释放其WLAN_INTERFACE_INFO数组结构
- 显示数组结构 c++
- C++ 使用函数访问数组结构的方法是什么?
- 将庞大的数组结构复制到 GPU
- 如何封送包含字符矩阵的数组结构
- C++多维数组结构的对齐