how to point to a pointer pointing to a dynamic array? - c++

create a dynamic array
int testSize = 10;
float *spec = new float[testSize];
how do you point to spec which points to the dynamic arary?
I tried this but It didn't work.
float **specPtr;
*specPtr = &spec[0];

float **specPtr;
specPtr = &spec;
spec is a pointer,so spePtr is the pointer that point to spec

Your problem is that by putting the dereference operator operator, you're assigning what the pointer specPtr points to, not what it actually is.
Try this instead
float **specPtr;
specPtr = &spec; // Note the omission of the '*'

Related

Is there a short way to convert a variable name into a double pointer?

For example:
int x = 7 // x is variable name
int* p_x = &x // p_x is a pointer to x
int** pp_x = &p_x // pp_x is a double pointer to x.
Is there a quick way to go from x to pp_x without using a intermediate variable p_x?
EDIT:
Thanks to the comments below I realized that such a thing isn't really possible because without p_x, pp_x would be pointless (No pun intended) because it wouldn't be pointing to anything.
If you are targeting anything above C99 you could use compound literals - like following:
int **pp_x = (int *[1]){(int[1]){7}};
int** pp_x = &p_x //pp_x is a double pointer to x.
It is a pointer to a pointer to x. So you must have p_x in order to have pp_x and you need to maintain p_x all the time you want access x via pp_x.

Understand how this double becomes an array?

So I'm currently reading and learning a code from the internet (related to artificial neural network) and I found a part of the code that I don't understand why it works.
double* inputNeurons;
double* hiddenNeurons;
double* outputNeurons;
This is how it was declared. Then in this next code, it was changed and used as an array?
inputNeurons = new( double[in + 1] );
for ( int i=0; i < in; i++ ) inputNeurons[i] = 0;
inputNeurons[in] = -1; // 'in' is declared in the function as an int
So, I want to understand why and how it works. Did it become an array of "doubles"? If so, in what way can I also use this? Can this be used for struct or even class?
Every array can be treated as a pointer. But that does not mean every pointer is an array. Do not mix this up!
Assuming we have an array int test[..], the variable name also represents the address where the array is stored in the memory. So you could write
int * p = test;
At that moment my pointer p "becomes" an array, where "becomes" means 'points to an array'. Your example is similar - the only difference is that the memory is allocated dynamically (heap) and not on the stack (as in my example).
So how are the elements accessed?
Let's say, we want to get the first element (index 0).
We could say
int i = test[0];
or we could say
int i = *p;
Now we want to get the element at index 1:
int i = test[1];
Or - by using pointer arithmetics we could write
int i = *(p + 1);
In C++ (and C) pointers support indexing operator [] which basically adjusts the value of the pointer by the amount specified times the size of the type pointed.
So basically
inputNeurons[5] = 0;
is equivalent to
*(inputNeurons+5) = 0
Now this doesn't give you any guarantee about the fact that inputNeurons points to an address which is correctly allocated to store at least 6 double values but syntactically it is correct and well defined.
You are just adjusting an address to point to the i-th element of a given type starting from the specified address.
This means that
double x;
double* px = &x;
px[5] = 0;
Is syntactically correct although it is wrong, since px+5 is an address which points to memory which has not been reserved correctly to hold that value.
The pointer of type double (double* inputNeurons;) just gets assigned to point to the beginning of an dynamically allocated array (new( double[in + 1])) of the same type. It does not become an array.
You can do this with any other pointer and regular array of the same type. As a matter of fact an array is a pointer to specific address (to its beginning, i.e. to the element with index: 0).
When you increment the pointer by + 1, that one means 1 * type_size (i.e 1 * size_of_double)
In your case: inputNeurons points to the address of the first element of the array. If you dereference it: *inputNeurons, you will get the value stored at that address (if inputNeurons was an array, it would be equivalent to: inputNeurons[0] ). To access the next element just increment by one (*inputNeurons + 1).

new operator with parentheses "(", ")" instead of brackets "[", "]"

I found a crazy mistake in my code.
I had written the following line:
GLfloat* points = new GLfloat(1024);
rather than
GLfloat* points = new GLfloat[1024];
I only just noticed it. My code has compiled and run a few times before I noticed the error. I realize that this is by fluke, but my question is what does the line I originally had do?
I notice that it looks kind of like the creation of a class using a pointer to allocated memory. Does it create a single GLfloat on the heap with the initial value of 1024.0? If this is true, why is it valid syntax? (GLfloat is not a class, is it?)
GLfloat is an OpenGL alias for float (i.e., typedef float GLfloat;). Consequently the code:
GLfloat* points = new GLfloat(1024);
Is equivalent to:
float* points = new float(1024);
Which allocates a floating point number and initializes it to 1024.0 and assigns its address to pointer points.
Yes, you are creating a single GLFloat on the heap initialized to 1024.0. You can initialize primitives with the same syntax as classes. e.g.
int i(10);
Would create an int on the stack initialized to 10.
what does the line I originally had do?
GLfloat* points = new GLfloat(1024);
Let us try to replace GLfloat with int, you will see that if GLFloat is a type similar to int or float, then you will have the following:
int * points = new int(1024);
The above statement means that you are creating a pointer to an int with initial value being 1024. So in your case, it means creating a pointer points to a variable with type being GLfloat and initial value as 1024.
It is equivalent to write the following in a condensed version:
int * points = new int;
*points = 1024;
See here for more explanation.

Is this the right way to initialize a pointer?

Is this the right way to use a function that writes to a pointer? Do I have to allocate memory for the double* before calling the function?
double *myDouble;
write_to_pointer( myDouble );
Do you mean it writes to the pointer itself, or to the memory it points to?
If it's the first, and it takes the pointer by reference, for example:
void write_to_pointer(double *& p) {
p = whatever;
}
then it's correct, although rather confusing. It would be better to return the value as a return value, so that the assignment is more obvious:
double *get_pointer() {return whatever;}
double *myDouble = get_pointer();
If it's the second, then no: the pointer doesn't point at anything, so attempting to dereference it will give undefined behaviour (typically crashing or corrupting some other program memory). It will need to point to a valid double (or a sufficiently large array of double, if that's what the function expects).
You can make pointers point to data in a variety of ways.
The following will create a single double on the heap, and will be pointed to by myDub. It will then assign the value of myDub to 4. It will then delete myDub and set the pointer to NULL.
double * myDub = new double;
*myDub = 4;
delete myDub;
myDub = NULL;
You can similarly allocate arrays.
double * myDub = new double[123];
myDub[0] = 4;
myDub[3] = 43;
delete[] myDub;
myDub = NULL;
And you can have pointers point to variables that already exist. (Note that I don't call delete in this case!)
double onStack = 4;
double * myDub = &onStack;
This is the wrong way to write to a pointer. Either allocate memory to your variable:
double *myDouble = new double;
write_to_pointer( &myDouble );
delete myDouble;
in this case declaration will be write_to_pointer( double** )
OR
declare your variable on stack:
double myDouble;
write_to_pointer( &myDouble );
in this case declaration will be write_to_pointer( double* )

How to convert double* to a double?

Any ideas for this typecasting problem?
Here's what I am trying to do. This is not the actual code:
LinkedList* angles;
double dblangle;
dblangle = (some function for angle calculation returning double value);
(double*)LinkedListCurrent(angles) = &double;
I hope you get the idea. The last line is causing the problem. Initially angles is void* type so I have to first convert it to double*.
You use the unary * operator to dereference a pointer. Dereferencing a pointer means extracting the value pointed to, to get a value of the original type.
// Create a double value
double foo = 1.0;
// Create a pointer to that value
double *bar = &foo;
// Extract the value from that pointer
double baz = *bar;
edit 2: (deleted edit 1 as it was not relevant to your actual question, but was based on a miscommunication)
From your clarification, it looks like you are wondering how to set a value pointed to by a pointer that has been cast from a void * to a double *. In order to do this, we need to use the unary * on the left hand side of the assignment, in order to indicate that we want to write to the location pointed to by the pointer.
// Get a void * pointing to our double value.
void *vp = &foo;
// Now, set foo by manipulating vp. We need to cast it to a double *, and
// then dereference it using the * operator.
*(double *)vp = 2.0;
// And get the value. Again, we need to cast it, and dereference it.
printf("%F\n", *(double *)vp);
So, I'm assuming that your LinkedListCurrent is returning a void * pointing to some element in the linked list that you would like to update. In that case, you would need to do the following:
*(double*)LinkedListCurrent(angles) = dbangle;
This updated the value pointed to by the pointer returned from LinkedListCurrent to be equal to dbangle. I believe that is what you are trying to do.
If you are trying to update the pointer returned by LinkedListCurrent, you can't do that. The pointer has been copied into a temporary location for returning from the function. If you need to return a pointer that you can update, you would have to return a pointer to a pointer, and update the inner one.
My explanation above is based on what I believe you are trying to do, based on the example snippet you posted and some guesses I've made about the interface. If you want a better explanation, or if one of my assumptions was bad, you might want to try posting some actual code, any error messages you are getting, and a more detailed explanation of what you are trying to do. Showing the interface to the linked list data type would help to provide some context for what your question is about.
edit 3: As pointed out in the comments, you probably shouldn't be casting here anyhow; casts should be used as little as possible. You generally should use templated collection types, so your compiler can actually do typechecking for you. If you need to store heterogenous types in the same structure, they should generally share a superclass and have virtual methods to perform operations on them, and use dynamic_cast if you really need to cast a value to a particular type (as dynamic_cast can check at runtime that the type is correct).
why on earth would you want to use a memory address as a floating point number?
if you meant dereference:
double d = 1.0; // create a double variable with value 1.0
double *dp = &d; // store its address in a pointer
double e = *dp; // copy the value pointed at to another variable
Note this line:
(double*)LinkedListCurrent(angles) = &double;
where you've written &double, it i think should be &dbangle. To improve readability, I would write:
((double*)LinkedListCurrent(angles)) = &dbangle;
However, you should not do this type of conversion as others mentioned.
Use a union. If you want the store two variables in one memory location (but not at the same time), you don't have to pretend that one is the other.
union double_and_ptr {
double d;
double *p;
};
double_and_ptr x, y;
x.d = 0.1;
y.p = &x.d; // store a pointer in the same place as a double
y.d = x.d * 1.2; // store a double in the same place as a ptr
Use reinterpret_cast.
double foo = 3.0;
double* pfoo = &foo;
double bar = reinterpret_cast<double>(pfoo);
In answer to this:
I want to do the opposite of what you have done here. I want to copy the value from the pointer to the d floating point number. How can I do that?
You would do something like this:
// declare a pointer to a double
double *pointer_to_double;
// declare a double
double my_double = 0.0;
// use the indirection operator (*) to dereference the pointer and get the value
// that it's pointing to.
my_double = *pointer_to_double;
This might be done like so in a real program:
void print_chance_of_snow(double *chance)
{
double d = *chance;
d = d * 100; // convert to a percentage
printf("Chance of snow is: %.2f%%\n", d);
}
int main(int argc, char *argv[])
{
double chance_of_snow = 0.45;
print_chance_of_snow(&chance_of_snow);
}