将数组赋值给结构指针

时间:2016-01-31 14:20:56

标签: c++ structure

尝试使用以下程序中的指针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;
}

2 个答案:

答案 0 :(得分:1)

变量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;
}

或者这是live demo

答案 1 :(得分:1)

省略这样的代码的想法对我来说是神秘的,这是导致错误的原因:
如果我们假设responseStruct的成员理想地匹配来自l_httpResponse的数据,sizeof(int)sizeof(unsigned char *)为4,那么您的架构使用小端符号,并且你的编译器使用ASCII(它可能会这样做),你得到:

Handle == 0x04030201
headerLen == 0x08070605
bodyLen == 0x02010009
content == 0x64636261

现在,content是一个指针,所以0x64636261是你内存中的一个地址。它没有指向你的“abcde ...”字符串。它由前四个字节组成。并指出一些不存在的地区。这就是你最终出现分段错误的原因。