c++ - 将结构指针数组传递给函数
问题描述
试图将结构指针数组传递给 function doIt()
。看起来我的方式不正确,因为我无法获得正确的第二个数组元素:
struct c {
int a;
char* b;
};
struct cc {
int a;
c* b;
};
char a[] = "aaa";
char b[] = "bbb";
char e[] = "eee";
c d1 = {1,a};
c d2 = {2,b};
c d3 = { 12,e };
cc g1 = { 123, &d1 };
cc g2 = { 321, &d2 };
cc g3 = { 333, &d3 };
void doIt( c * s)
{
cout << s->b;
s++;
cout << s->b;
}
传递结构指针数组的正确方法是什么?
解决方案
C(和 C++)中的原始数组只是指针。它们指向数组的第一个元素。例如,如果你想要一个 数组int
,你可以这样写int* array
。如果你想要一个数组struct c
,你可以这样写c* array
。如果你想要一个指向 的指针数组struct c
,你可以这样写c** array
。
要访问元素,不要使用array++
,使用array[i]
wherei
是要访问的元素的索引(位置),0 是第一个元素的索引,1 是第二个,等等。
因此,您的代码应如下所示:
void doIt(c** s)
{
cout << s[0]->b; // s[0] is the first element
cout << s[1]->b; // s[1] is the second
}
请注意,在 C++ 中,最好使用std::vector
原始数组而不是原始数组。
void doIt(std::vector<c*> s)
{
cout << s[0]->b;
cout << s[1]->b;
}
推荐阅读
- android - 未解决的参考:在 lateinit 属性上的 isInitialized
- c# - Autofac 程序集扫描注册期间未找到程序集错误
- python - 如何找到给定数字中有多少个数字?
- c - 如何在C中找到数组中的最大和最小元素?
- c# - 切换开关在 AJAX 加载的视图中不起作用
- reactjs - 使用 UseState React Hook 从子组件更新父组件状态
- python - 为 python 设置 coc.nvim
- python - 如何计算一个非常非常大的数字并将其写入python中的文件?
- oauth-2.0 - 从 1 个刷新令牌生成不同的访问令牌范围
- matlab - 如何使用matlab制作图表