pavikirthi pavikirthi - 5 months ago 12
C++ Question

difference between creating a pointer struct member variable with new and creating a general struct in a linked list data structure

There a struct which is named as "number", so I came across two methods of creating a member variable of struct, first one by creating a pointer member variable and the second one without a pointer variable as shown below in the code.So, what is the difference between the two is there any merits/ demerits and which one is a good programming technique - method 1 or method 2 or is there any other better method to create a struct variable ?

struct number
int val;
number *next;

number *lastnumber;

int main()
lastnumber = NULL;

return 0;

**Method 1**
void add_value(int value)
number *latest = new number; //initialization
latest->val = value;
latest->next = lastnumber;
lastnumber = latest;

**Method 2**
void add_value(int value){
number latest;
latest.val = value; = lastnumber;
lastnumber = &latest;


As far as I know, if you use new, new memory gets allocated of the size of you struct, and later, when you have finished using the struct (the memory it obtained), you have to manually delete it with delete.

If you dont use new like in method 2, the memory management is automatically done using local memory lifetime management when it goes out of scope (Im just guessing - idk if there is any garabage collection or how it works). However, with not using new, you dont have to free the memory manually.

Thats the only difference between methods 1 and 2 - Each time, memory is allocated of the size of your struct, but in method 1 you just have a pointer to this memory, which you have to delete afterwards to avoid memory leaking, while in method 2 the variable "is" the memory.