struct x {
unsigned int y;
unsigned int *ptr;
};
std::vector<struct x> z;
I want to access the integer array pointed to by ptr
. z[0].y
will properly return the element y
from the first struct in the vector.
我想访问ptr指向的整数数组。 z [0] .y将正确地从向量中的第一个结构返回元素y。
How can I print the array pointed to by ptr inside of the first struct?
如何打印第一个结构中ptr指向的数组?
2 个解决方案
#1
0
z[0].ptr
will return the ptr
from the first struct in the vector. To access an element of the array this points to, use z[0].ptr[n]
.
z [0] .ptr将从向量中的第一个结构返回ptr。要访问此指向的数组元素,请使用z [0] .ptr [n]。
#2
0
The same way as you access z[0].y
:
与访问z [0] .y的方式相同:
z[0].ptr;
However you have to know the array size, if you want to iterate and print its elements. Probably you want to keep an additional unsigned int size;
inside your struct
.
但是,如果要迭代并打印其元素,则必须知道数组大小。可能你想保留一个额外的unsigned int大小;在你的结构中。
You access the elements of the array as usual:
您可以像往常一样访问数组的元素:
for(unsigned int i=0;i<z[0].size;i++)
std::cout << z[0].ptr[i] << std::endl;
If your array can change in size, and you don't want to store an additional variable, just use std::vector
like you did to store your structs.
如果您的数组可以更改大小,并且您不想存储其他变量,只需使用std :: vector就像存储结构一样。
Remember to first create the array using new[]
and then delete its contents using delete[]
when you don't need it. Trying to access memory that doesn't belong to you, will lead to undefined behaviour.
请记住首先使用new []创建数组,然后在不需要时使用delete []删除其内容。尝试访问不属于您的内存将导致未定义的行为。
#1
0
z[0].ptr
will return the ptr
from the first struct in the vector. To access an element of the array this points to, use z[0].ptr[n]
.
z [0] .ptr将从向量中的第一个结构返回ptr。要访问此指向的数组元素,请使用z [0] .ptr [n]。
#2
0
The same way as you access z[0].y
:
与访问z [0] .y的方式相同:
z[0].ptr;
However you have to know the array size, if you want to iterate and print its elements. Probably you want to keep an additional unsigned int size;
inside your struct
.
但是,如果要迭代并打印其元素,则必须知道数组大小。可能你想保留一个额外的unsigned int大小;在你的结构中。
You access the elements of the array as usual:
您可以像往常一样访问数组的元素:
for(unsigned int i=0;i<z[0].size;i++)
std::cout << z[0].ptr[i] << std::endl;
If your array can change in size, and you don't want to store an additional variable, just use std::vector
like you did to store your structs.
如果您的数组可以更改大小,并且您不想存储其他变量,只需使用std :: vector就像存储结构一样。
Remember to first create the array using new[]
and then delete its contents using delete[]
when you don't need it. Trying to access memory that doesn't belong to you, will lead to undefined behaviour.
请记住首先使用new []创建数组,然后在不需要时使用delete []删除其内容。尝试访问不属于您的内存将导致未定义的行为。