0

What is new int in c++

6th Jan 2018, 7:38 AM
Sandeep Rana
5 Answers
+ 6
new allocated a memory in the RAM for this variable int declares the type of the variable, which have different storage requirements. Then you declare the variable name. Immediately after/Later, you assign a value
6th Jan 2018, 8:53 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 5
When you declare a pointer, you may either pass it the address of an existing variable, or you may allocate memory for it in the RAM to store variables in the dynamic memory of the computer. To allocate new memory in the dynamic memory section of the computer, C++ offers the user the keyword new. This keyword allocates memory for the provided pointer. The syntax for new is : type* ptr = new type; // allocate memory for a single type variable. Eg - int* ptr = new int; One can also use new to allocate contiguous blocks of memory like an array. Eg - int* arr = new int[20]; // Array of size 20.
6th Jan 2018, 8:41 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 2
To start with: the "NEW" keyword is used to allocate memory from the heap(heap is unused dynamic memory of the program[dynamic memory is the memory used during runtime]) for example, "int" has a 4-byte memory(static memory) which can store up to some range of integers. but sometimes, you don't know the value of your integer. If it exceeds the range of integers, you won't get a right output. At times like this, declaring "new int" will allocate memory from the unused dynamic memory to the integer whenever your integer value exceeds its range. "New" can also be used on other data types like float etc.(doesn't work on bool and char as it has just has one as range and 1 byte memory)
6th Jan 2018, 8:33 AM
Sujan Veena
Sujan Veena - avatar
+ 1
@Kinshuk Vasisht Hey... thanks.... I almost got messed up with the concept... With your answer, I remembered it was for pointers. You are right! Still shows I have a long way to go!! Cheers man!
6th Jan 2018, 10:24 AM
Sujan Veena
Sujan Veena - avatar
0
@Sujan Veena Can you tell me why these statements are invalid? char* str1 = new char; *str1 = 'e'; cout<<*str1; bool* rf = new bool, done = false; rf = &done; *rf=true; cout<<done; The truth is, they aren't. You can do these. There is no restriction on allocation of a single byte using new. I mean, why should there be a restriction in the first place? Secondly, new doesn't add memory to an int variable so that it can store larger values. No function can alter the amount of bytes used by a fundamental type. The purpose of new is to simply reserve memory for storing an int variable on the heap instead of the traditional stack. The main advantage of using heap is that you can store a large number of int variables like in an array of 100000 elements easily on the heap. But all of them have the fixed range of 4 bytes, and that cannot be altered. Correct me, if I am wrong.
6th Jan 2018, 9:21 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar