[英]What is right way to access elements of std::array by passing as a pointer to function in C++?
The code snippet is as follows. 代码段如下。 The error is in foo function for the cout line:
错误是在cout行的foo函数中:
typedef struct Datatype {
int first;
int second;
} Datatype;
void foo(std::array<Datatype, 100>* integerarray){
cout << *integerarray[0].first << endl; //ERROR: has no member first
}
void main() {
std::array<Datatype, 100> newarray;
for(int i=0; i<100; i++)
newarray[i] = i;
}
foo(&newarray);
}
Because of operator precedence, *integerarray[0].first
is translated as *(integerarray[0].first)
, which is not what you want. 由于运算符的优先级,
*integerarray[0].first
转换为*(integerarray[0].first)
,这不是您想要的。 You need to use (*integerarray)[0].first
. 您需要使用
(*integerarray)[0].first
。
cout << (*integerarray)[0].first << endl;
You can make your life simpler by passing a reference. 通过传递参考可以使您的生活更简单。
void foo(std::array<Datatype, 100>& integerarray){
cout << integerarray[0].first << endl;
}
Also, you don't need to use typedef struct DataType { ... } DataType;
另外,您不需要使用
typedef struct DataType { ... } DataType;
in C++. 在C ++中。 You can use just
struct DataType { ... };
您可以只使用
struct DataType { ... };
In this line you have missed adding value to structure variables. 在这一行中,您错过了为结构变量添加值的过程。 Also you have passed array as a reference to function.
另外,您已将数组传递为函数的引用。 Removing it and passing just the name of array will pass base address of array.
删除它并仅传递数组名称将传递数组的基地址。 I am adding following code for your reference:
我添加以下代码供您参考:
#include<iostream>
#include <array>
struct Datatype{
int first;
int second;
}
typedef Datatype varInts;
void display(std::array<varInts,20> &dummy)
{
int b =5;
for(int i=0; i<20; i++)
{
dummy[i].first =b++;
dummy[i].second = b+5; //Give any logic you wish.just adding different values;
b++;
}
}
int main()
{
std::array<varInts,20> data;
int a =1;
for(int i=0;i<20;i++)
{
data[i].first = a++;
data[i].second = a+5;
a++; //Just adding values for example
}
display(data);
return 0;
}
It runs without error.Hope it helps!! 它运行没有错误,希望能有所帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.