This question already has answers here:
When should I use the new keyword in C++?
(12 answers)
Closed 7 years ago.
Is there any difference between these 2 ways of storing an integer?
int X = 100;
and
int *pX = new int(100);
"Is there any difference between these 2 ways of storing an integer?"
Yes, there is a significant difference.
int X = 100;
Initializes a variable X on the stack with the value 100, while
int *pX = new int(100);
allocates memory for an int on the heap, kept in pointer pX, and initializes the value to 100.
For the latter you should notice, that it's necessary to deallocate that heap memory, when it's no longer needed:
delete pX;
The first one is creating a variable on the stack while the second one is creating a variable on the heap and creating a pointer to point at it.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
Improve this question
As the title suggests,
int [] a = new int[size];
constantly throws me an error.
I am not yet familiar with C++ so please help me tweak the code above to as closely similar to the syntax above (above was a given pseudo(?) code in a class) so I can create an array.
Thank you.
#include <iostream>
using namespace std;
// Test program
int main( )
{
int [] a = new int[10];
cout << a[0];
return 0;
}
Tried running the above code and it failed to compile.
new is for dynamic allocation (of an array on the heap in this case), and returns a pointer to the new array.
[] in the declaration are for declaring it to be a stack array (and the brackets belong the right side of the variable name).
So the two legal approaches your code is mixing would simplify to either:
int a[10]; // Declares a stack array of size 10
or:
int *a = new int[10]; // Dynamically allocates a heap array of size 10 and stores the pointer to it in `a`
The former is the better solution here (there's no benefit to a heap allocation for such a small array that is only used within the scope of this function, and it would require explicit delete[] a; later to properly clean it up).
That said, neither version initializes the values, so the contents of a[0] are uninitialized, and reading from them will get random garbage. Both versions can be changed to initialize the data with zeroes though, e.g.:
int a[10] = {0}; // Declares a stack array of size 10 and initializes to zero
or:
int *a = new int[10](); // Dynamically allocates a heap array of size 10 and stores the pointer to it in `a`, initializing to zero
Final note: Using raw new is generally frowned upon in modern C++. If you needed heap-allocated contiguous data storage, you're probably better off using a std::vector.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have 3 questions:
Q1. When we create the object using the new operator, following is the syntax:
pointer_variable = new data-type //To create an object
pointer_variable = new data-type(value); //To create an object with value
pointer_variable = new data-type[size]; //To create an array
Why always there is a pointer_variable on L.H.S?
Q2. What is the difference between declaring and assigning pointers with and without the new operator?
Consider the following code snippet and output to understand the question:
int a = 10, b=20;
int *p;
p = &a;
int *q = new int;
q = &b;
cout<<"P is: "<<p<<" : "<<*p<<endl<<"Q is: "<<q<<" : "<<*q<<endl;
Output of the above code:
P is: 0x61ff04 : 10
Q is: 0x61ff00 : 20
Q3. When we say, with a new operator we can dynamically allocate memory to the array at run time when we don't know the size of the array at compile time. We can do this without new operator as given below:
cout<<"Enter the size of an array"<<endl;
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
for(int i=0;i<n;i++)
{
cout<<arr[i];
}
Then what is exactly the need to use the new operator for arrays?
Why always there is a pointer_variable on L.H.S?
Because new-expression results in a pointer.
What is the difference between declaring and assigning pointers with and without the new operator?
new-expression (not operator new) constructs a new object (and, optionally, allocates memory for it).
We can do this without new operator as given below
In fact, we cannot, according to the C++ Standard. Some compilers just allow this construct as a non-standard language extension.
Every good C++ book for beginners will explain these in more details.
in C++, a typical new expression allocates memory on the heap, and returns a pointer to that memory.
Re Q1: you can save the resulting pointer to a local variable for immediate use: pointer_variable = new int. But you don't have to do that: you could instead use it as an argument to a function: use_pointer(new int).
Re Q2: your code allocates an int on the heap, stores its pointer in local variable q, and immediately overwrites it with the address of local variable b. So what you have done here is write a small memory leak.
Re Q3: variable-sized array is a nonstandard extension to C++, so it will not necessarily work in another compiler. However, when it does work it is just another automatic variable: it will be automatically de-allocated for re-use when you leave the local scope. This is different from new allocations, which last until they are explicitly delete-ed.
This question already has answers here:
How to create an array when the size is a variable not a constant?
(6 answers)
Closed 3 years ago.
How to use the the value stored in a int variable as the size of my array
eg.
int a = 40;
int b[a]; // a = 40
You can't; not in standard C++ anyway, unless a is a constexpr or const integral type with a positive value.
The best alternative is a std::vector<int> b(a);
Create an array with new[]:
int *b = new int[a];
but remember to delete it later with:
delete[] b;
A better alternative is the std container, like std::vector.
This question already has answers here:
C++ new int[0] -- will it allocate memory?
(6 answers)
Closed 5 years ago.
I dynamically allocated an array (unsigned int n might have been passed as a parameter in a function):
int * ar = new int [n];
When I'm done using it:
delete [] ar;
But, what happens when n = 0?
Is allocate 0 ints the same as not allocating at all?
In which case, do bad things happen when I call delete?
It's ok to new a zero-sized array, and to delete it. This is more of a convenience than anything, as it means you don't have to write separate conditions for the 0 case.
This question already has an answer here:
C++ Struct Pointer Segfault
(1 answer)
Closed 9 years ago.
I'm new to C++ and pointers and wrote a simple cpp below. I keep on getting a seg fault, but I'm not sure why.
int main() {
int *x = 0;
*x = 8;
return 0;
}
Your integer pointer is null. See this line:
int *x =0
On that line you're setting the memory address of your integer pointer to zero (i.e. nullptr). What I expect you wanted to do is set the value to zero, in which case you'd need to do this:
int main() {
int *x = new int(0);
*x = 8;
return 0;
}
You've declared a pointer to an integer and set it to 0. You haven't actually allocated an integer anywhere. When you assign 8 to the dereferenced pointer, you're trying to write to the memory at location 0. All modern operating systems read and write product the memory at address 0 and anywhere near it to prevent this kind of 'null pointer error'.
Think of memory on a computer as a sheet of graph paper. Each square on the paper has an address, which is the number of squares that came before it. Pointers are for storing these addresses. An int is an actual value, like '5 apples' or '12 downvoting asshats'. These are the values that are stored by writing a number inside one of the rectangles.
However, the OS that manages the system knows that one of the most common kinds of errors people make is forgetting to set up a pointer properly and attempting to write numbers at the very start of the graph paper, so it's designed the graph paper to give you an electric shock if you try to write a number in any of the first few boxes. This is your segmentation fault.
To fix the issue you can either declare an integer on the stack
int i;
int * x = &i;
Declaring something on the stack means the memory will automatically be freed when it leaves scope, i.e. the end of the function.
On the other hand you can allocate a pointer on the heap
int * x = new int;
this means that you're personally responsible for making sure that you free the memory at some later point.
delete x;
Otherwise you're creating a memory leak.
When you define int *x = 0, what you're telling the compiler is "create a integer pointer, x, and set where it points to to 0 (NULL)". What you need to do instead is dynamically create a new pointer. This can be achieved by doing int *x = new int; Then you can change its value. After using it, you should delete it using delete x; to free up its memory.
int *x = 0;
You made an int pointer called x which points to the memory at location 0.
*x = 8;
You tried to write the value 8 into the memory at location 0, which was stored in x. Since this memory is not owned by you, the OS terminated you.
Let's break this down a bit:
int *x = 0
this line creates a pointer called x and points it to NULL (or nowhere)
*x = 8
There is an immediate issue here as soon as you "dereference" x, meaning asking for the spaces associated what x points to.
Since you pointed x at NULL you're asking for the int located at NULL. This is illegal as NULL is an invalid memory space causing a seg-fault.