문제

I want to make a memory allocation of a struct like the following in C++. Is it fine to do it like:

m_temppkt = new pktstruct();

and the struct is:

 struct pktstruct {
   void *address;
   int length;
   struct pktstruct *next;
 };
도움이 되었습니까?

해결책

It is fine to do that, but the memory in m_temmkt->address will not be allocated (i.e. you allocate space for the pointer, not for the memory the pointer will point to).

The best solution is to initialize the values using a constructor:

struct pktstruct {
    void *address;
    int length;
    struct pktstruct *next;
    pktstruct(void* s, int l);
};

pktstruct::pktstruct(void* a, int l)
: address(a), length(l), next(NULL)
{
}

m_temppkt = new pktstruct(NULL, 0); // initializes with { NULL, 0, NULL }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top