-4

In C++, I have seen 2 ways to create a new struct:

1.

StructA a;
a.member1 = ...;
foo(&a); // void foo(StructA* a);

2.

StructA* a = new StructA;
a->member1 = ...;
foo(a);

What are the difference and implications of these 2 code snipets?

Thanks

cody
  • 651
  • 2
  • 8
  • 16
  • The second one is a pointer to a struct; the first is a direct variable declaration. – Govind Parmar Oct 13 '14 at 22:52
  • What do you think is the difference? I'm asking to understand how/what to answer, since your answer will give me a "level". – Mats Petersson Oct 13 '14 at 22:52
  • 1
    The second one requires you to now manage what you just allocated. – chris Oct 13 '14 at 22:52
  • 1
    possible duplicate of [What and where are the stack and heap?](http://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap) – harmic Oct 13 '14 at 23:07
  • Thanks Chris & harmic. No thanks to those downvoters who didn't care to give a reason! – cody Oct 13 '14 at 23:22
  • The downvotes are because you should know the answer to this after finishing a C++ tutorial. – Neil Kirk Oct 13 '14 at 23:42
  • In addition to the other comments above and below, the first declaration allocates the space for the structure from the stack (typically), and the second declaration allocates space for the structure from the heap. The pointer in the second declaration could be stored on the stack or in a register, depending on how the compiler optimizes the code. – rcgldr Oct 14 '14 at 00:48

1 Answers1

0

The difference in a nutshell:
StructA a declares a variable that is a StructA.
StructA* a declares a pointer that points to a StructA.

The implications:

The variable StructA is can be immediately used to store data.
The pointer StructA* must be set to point to an actual struct before it can be used to store data.

The variable StructA will automatically be deallocated when the current block exits.
While the pointer StructA* will be deallocated when the current block exits, the data it is pointing to (created with new) will not go away until delete is called. If delete is never called, then your program will have a memory leak.

Louis Newstrom
  • 172
  • 1
  • 1
  • 13