Allan Jiang
Allan Jiang

Reputation: 11331

C++ Struct Dynamic Memory Allocation

I have a struct defined like this:

Struct Example
{
 char arr[MAX_SIZE];
};

In a C-style, I can do Example * pExample = (Example*) malloc(sizeof(Example)); to get a pointer to a dynamically allocated memory. Now I want to know if there's any way I can do the same thing using auto_ptr smart pointer, without any change on the data structure.

Thank you

Upvotes: 0

Views: 5679

Answers (1)

David G
David G

Reputation: 96810

The equivalent C++ code would be:

Example *pExample = new Example();

But if you need a smart pointer I wouldn't recommended auto_ptr because it has been deprecated. Rather, use something like shared_ptr, or std::unique_ptr (C++11):

std::shared_ptr<Example> pExample;

Upvotes: 2

Related Questions