制作可变大小的结构体的方法 [英] Method for making a variable size struct

查看:187
本文介绍了制作可变大小的结构体的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要制作一个包含标题,预告片和可变长度有效字段的数据包。到目前为止,我一直使用一个向量的有效负载,所以我的结构是这样设置:

  struct a_struct {
hdr a_hdr;
vector< unsigned int> a_vector;
tr a_tr;
};

当我尝试访问向量的成员时,我得到一个seg错误和一个整数structs的sizeof给我32(在我向向量中添加了大约100个元素之后)。



这是一个好方法吗? b $ b

我发现这篇文章
http://stackoverflow.com/questions/ 688471 / variable-sized-struct-c
他使用的是char数组,我使用的是一个向量。

解决方案

另一个SO答案中的解决方案是c特定的,并依赖于c数组的特性 - 甚至在c中,sizeof()将无法帮助你找到真



你所做的是很好的,为了避免seg错误,像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


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 http://stackoverflow.com/questions/688471/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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆