制作变量大小的方法 [英] Method for making a variable size struct
问题描述
struct a_struct {
hdr a_hdr;
vector< unsigned int> a_vector;
tr a_tr;
};
当我尝试访问向量的成员时,我得到一个seg错误和一个sizeof的整个结构给我32(在我向矢量中添加了大约100个元素之后)
这是一个很好的方法吗?更好吗?
我发现这个帖子
变量大小的Struct C ++
他正在使用一个char数组,而我正在使用一个向量。
其他SO答案中的解决方案是c特定的,依赖于c数组的特殊性,即使在c中,sizeof()也不会帮助你找到一个变量大小的true大小的结构体,这本质上就是作弊,这是一种欺骗这在C ++中是不必要的。
你在做什么是好的,为了避免seg错误,请像C ++中的其他向量一样访问向量:
a_struct a;
for(int i = 0; i <100; ++ i)a.a_ vector.push_back(i);
cout<<< a.a_vector [22]<<终点//打印22
I need to craft a packet that has a header, a trailer, and a variable length payload field. So far I have been using a vector for the payload so my struct is set up like this:
struct a_struct{
hdr a_hdr;
vector<unsigned int> a_vector;
tr a_tr;
};
When I try to access members of the vector I get a seg fault and a sizeof of an entire structs give me 32 (after I've added about 100 elements to the vector.
Is this a good approach? What is better?
I found this post Variable Sized Struct C++ He was using a char array, and I'm using a vector though.
The solution in the other SO answer is c-specific, and relies on the peculiarities of c arrays - and even in c, sizeof() won't help you find the "true" size of a variable size struct. Essentially, it's cheating, and it's a kind of cheating that isn't necessary in C++.
What you are doing is fine. To avoid seg faults, access the vector as you would any other vector in C++:
a_struct a;
for(int i = 0; i < 100; ++i) a.a_vector.push_back(i);
cout << a.a_vector[22] << endl; // Prints 22
这篇关于制作变量大小的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!