I would like to assign integer 1 to double* queue[i].. I need to convert int 1 to double* type value first before I can assign it to queue[i].. How to code this?
-
Welcome to Stack Overflow. Please read [the help pages](http://stackoverflow.com/help), take the SO [tour], read [ask], as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). Lastly please learn how to create a [mcve] of your own attempt, and [edit] your question to show it together with a detailed description of the problems with it (as long as a description of the problem you try to solve). – Some programmer dude Apr 06 '20 at 06:18
-
You can't convert `1` to a `double*`. Please read [What is the XY problem?](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) – molbdnilo Apr 06 '20 at 06:25
2 Answers
I would like to assign integer 1 to double* queue[i]
I think you meant to add the value 1 into your queue:
queue[i] = new double(1.0);
Assigning a direct address is a different story.
I need to convert int 1 to double* type value first before I can assign it to queue[i]
That's not how your dynamic queue
works. It stores the address of newly allocated memory for every double
. The new
operator is used for this purpose and it will return the necessary pointer, you just need to do the dynamic memory allocation properly.

- 3,777
- 9
- 27
- 53
Do you want to assign a direct address to a pointer variable? You had better use &
operator or +
, ++
operators on known functions or variables to get the addresses. It's unsafe and not recommended to hardcode address in code. Each time the program is loaded into memory, it could be a different memory space, so the hardcoded address will cause segmentation fault.
See the following example. Either queue[1]
assignment or queue[2]
assignment is not recommended.
#include <stdio.h>
#define MAX_SIZE 10
void print(double *p, int i)
{
printf("queue[%d]=%p\t*queue[%d]=%.2f\n", i, p, i, *p);
}
int main()
{
double *queue[MAX_SIZE];
double dval = 3.5f;
int ival = 1;
queue[0] = &dval;
print(queue[0], 0);
// queue[0]=0x7ffee2bfca20 *queue[0]=3.50
queue[1] = &ival;
print(queue[1], 1);
// queue[1]=0x7ffee2bfca1c *queue[1]=0.00
queue[2] = ((double *)1);
print(queue[2], 2);
// zsh: segmentation fault
return 0;
}

- 86
- 6