C ++中具有动态大小的嵌套结构

时间:2019-02-03 16:14:04

标签: c++ data-structures dynamic struct nested

我正在尝试在showValues(mainStruct *)中打印数据,但是我无法这样做。

#include <iostream>
#include <string>
#include <vector>
#include <memory>

typedef struct
{
  uint32_t someNumber;    
}subStruct;

typedef struct{
    uint32_t sizeofSubStruct;
    subStruct subStructArray[1];
}mainStruct;

此函数构造mainStruct并用一些值填充

mainStruct* constructMainStruct()
{
    mainStruct* msPtr;
    msPtr = (mainStruct*)malloc(sizeof(mainStruct)*10);
    msPtr->sizeofSubStruct = 10;

    subStruct* ssPtr = msPtr->subStructArray;
    for(uint32_t i=0; i < msPtr->sizeofSubStruct; i++)
    {
        ssPtr->someNumber = i+10;
        ssPtr++;       
    }             
    return msPtr;
}

以下功能无法打印任何内容

void showValues(mainStruct* msPtr)
{
    subStruct* ssPtr = msPtr->subStructArray;
    for(uint32_t i=0; i < msPtr->sizeofSubStruct; i++)
    {   
     std::cout << " - " + ssPtr->someNumber <<std::endl;
    }
}

主要功能

int main()
{
    //contructing mainStruct with some values
    mainStruct* msPtr = constructMainStruct();

    //trying to print values which has been created in above step
    showValues(msPtr);
}

3 个答案:

答案 0 :(得分:3)

您的打印问题(绝不是唯一的问题)在一行中:

for(uint32_t i=0; i > msPtr->sizeofSubStruct; i++)

您将i初始化为0,但是使用“ i> msPtr-> sizeofSubStruct;”测试,该值应小于或大于。

其他问题与您的分配大小有关,应该是sizeof(mainStruct)+ sizeof(subStruct)* 9,这对您现在拥有的subStruct来说不是一个大问题,但是一旦subStruct变得复杂起来,它就会成为问题。

答案 1 :(得分:1)

除了@SoronelHaetir已经注意到的功能之外,函数showValues并没有增加subStruct指针。

代码应如下所示;

void showValues(mainStruct* msPtr)
{
    subStruct* ssPtr = msPtr->subStructArray;
    for (uint32_t i = 0; i < msPtr->sizeofSubStruct; i++)
    {
        std::cout << " - " + ssPtr->someNumber << std::endl;
        ++ssPtr;
    }
}

答案 2 :(得分:0)

以下是showValues的工作代码

void showValues(mainStruct* msPtr)
{
    subStruct* ssPtr = msPtr->subStructArray;
    for(uint32_t i=0; i < msPtr->sizeofSubStruct; i++)
    {   
     std::cout << (ssPtr+i)->someNumber <<std::endl;
    }
}

,完整的程序代码如下:

#include <iostream>

typedef struct
{
  uint32_t someNumber;    
}subStruct;

typedef struct{
    uint32_t sizeofSubStruct;
    subStruct subStructArray[1];
}mainStruct;

mainStruct* constructMainStruct()
{
    mainStruct* msPtr;
    msPtr = (mainStruct*)malloc(sizeof(mainStruct)*10);
    msPtr->sizeofSubStruct = 10;

    subStruct* ssPtr = msPtr->subStructArray;
    for(uint32_t i=0; i < msPtr->sizeofSubStruct; i++)
    {
        ssPtr->someNumber = i+10;
        ssPtr++;       
    }             
    return msPtr;
}
void showValues(mainStruct* msPtr)
{
    subStruct* ssPtr = msPtr->subStructArray;
    for(uint32_t i=0; i < msPtr->sizeofSubStruct; i++)
    {   
     std::cout << (ssPtr+i)->someNumber <<std::endl;
    }
}

int main()
{
    //contructing mainStruct with some values
    mainStruct* msPtr = constructMainStruct();

    //trying to print values which has been created in above step
    showValues(msPtr);
}