I'm new in c++.
There is a struct named node.
Why is
node* a = NULL;
a = new node;
possible, but
double* d = NULL;
d = 12.0;
is not? I just don't get WHY this doesn't work...
Thanks a lot
I'm new in c++.
There is a struct named node.
Why is
node* a = NULL;
a = new node;
possible, but
double* d = NULL;
d = 12.0;
is not? I just don't get WHY this doesn't work...
Thanks a lot
Here you go:
double* d = NULL;
d = new double;
*d = 12;
Remember to delete d
when you are done with it.
You can create struct or doubles with new. You can create structs or doubles without new. There's no difference between structs and doubles (in this regard).
node* a = new node;
double* b = new double(12.0);
node c;
double d = 12.0;
a
and b
have been created with new
, c
and d
have been created without new
.
for type double
you are initializing to NULL
and then making it to point to 12.0
, which is totally wrong. To write into the memory that your pointer points to you have to deference it: *d
and to deference d
you have to make sure that it actually points to a valid point in memory. using a new must come with a delete
when you are finished. You may use smart pointers instead to not to deal with memory leaks. Here is an example:
#include <memory>
#include <iostream>
int main() {
std::unique_ptr<double> a;
a.reset(new double);
*a.get() = 12;
std::cout <<*a.get();
}
see the compile here: https://godbolt.org/z/zHfE8O
In this code snippet
node* a = NULL;
a = new node;
the type of the expression new node
is node *
. So the left and right sides of the expression statement
a = new node;
has the same type. That is you can assign an object of the type node *
with another object of the same type node *
.
In this code snippet
double* d = NULL;
d = 12.0;
the type of the variable d
is double *
but the type of the float literal 12.0
is double
.
So the left and right sides of the expression statement
d = 12.0;
have different types and there is no implicit conversion from the type double
to the type double *
.
So the compiler will issue an error.
If you want to write a value to a memory pointed to by the pointer d
you have at first to allocate the memory where you are going to write the value 12.0
.
You can do it the following way
double* d = new double;
*d = 12.0;
Or you can do this in one line
double *d = new double( 12.0 );
Consider a situation with the structure node.
Let's assume that node is declared the following way
struct node
{
double value;
node *next;
};
and there is a declaration
node *a = NULL;
So this statement
a = new node;
only allocates memory to the node but does not sets values for its data members.
So to set values for the node you can write after allocating memory
( *a ).value = 12.0;
( *a ).next = NULL;
or (that is the same)
a->value = 12.0;
a->next = NULL;
All this also can be done in one line
node *a = new node { 12.0, NULL };