将数组分配给结构指针
assign array to structure pointer
在
下面的程序中尝试使用指针l_pContent打印内容成员时出现分段错误。
#include <iostream>
#include <string.h>
using namespace std;
struct responseStruct {
int Handle;
int headerLen;
int bodyLen;
unsigned char* content;
};
int main()
{
unsigned char l_httpResponse[] = {1,2,3,4,5,6,7,8,9,0,1,2,'a','b','c','d','e','f','g','h','i','j','k','l','a','b','c','d','e','f','g','h','i','j','k','l',0};
struct responseStruct *l_pContent = (struct responseStruct*)l_httpResponse;
cout << l_pContent->content << endl; // Error : Segmentation Fault
return 0;
}
变量 content
是指向unsigned char
的指针,l_httpResponse
也是如此。因此,您可以创建responseStruct
的实例,然后将该实例的content
指针分配给l_httpResponse
。
下面是一个示例:
#include <iostream>
#include <string.h>
using namespace std;
struct responseStruct {
int Handle;
int headerLen;
int bodyLen;
unsigned char* content;
};
int main()
{
unsigned char l_httpResponse[] = {1,2,3,4,5,6,7,8,9,0,1,2,'a','b','c','d','e','f','g','h','i','j','k','l','a','b','c','d','e','f','g','h','i','j','k','l',0};
// Create instance of an responseStruct struct
responseStruct rs;
// Make content point to the start of l_httpResponse
rs.content = l_httpResponse;
// Test for access without segfault
cout << static_cast<unsigned>(rs.content[1]) << endl;
return 0;
}
或者这是一个现场演示。
省略了这种代码的想法对我来说很神秘的事实,以下是导致错误的原因:
如果我们假设responseStruct
的成员将理想地匹配来自l_httpResponse
的数据,sizeof(int)
和sizeof(unsigned char *)
为 4,您的架构使用小端表示法,并且您的编译器使用 ASCII(它可能确实如此),则以:
Handle == 0x04030201
headerLen == 0x08070605
bodyLen == 0x02010009
content == 0x64636261
现在,content
是一个指针,所以0x64636261是你记忆中的一个地址。它没有指向你的"abcde..."字符串。它由前四个字节组成。并指向一些不存在的区域。这就是为什么你最终会出现分段错误。
相关文章:
- 如何在 C# 中映射双 C 结构指针?
- C++:映射结构中的结构指针
- C++:添加新结构时,结构指针向量中的所有元素都会更新
- 类的静态结构指针声明在C++
- 在两个.cpp文件之间定义全局类/结构指针
- 返回对常量结构(指针类型)成员的引用:明显的左值到右值转换
- 是否可以将无符号字符数组reinterpret_cast到仅包含C++中无符号字符成员的结构指针
- 如何在地图中使用结构指针
- 结构指针在"新"调用上给出已分配的地址?
- 铸造结构指针指向C 的工会指针
- c++ 结构指针在初始化为 NULL 时无法读取内存
- 函数中的结构指针的地址为0x1
- C 用结构指针初始化结构
- C 结构指针铸成数组Interop C#
- 方法中不允许访问结构指针
- 如何打印出结构指针
- MPI_Op_create:候选功能不可行.自定义结构指针不能解释为空指针
- 尝试将结构指针传递给类时出错
- 初始化结构指针的值
- 使用 pybind11 将自定义结构(指针向量)从 C++ 传递到 python 的方法是什么?