how to declair a pointer ....
You can declare a pointer (to double
) like this:
double* ptr;
... at a memory location ...
You can initialise the pointer with a memory location:
double* ptr = some_address;
Or assign it after declaration:
ptr = some_another_address;
and a initilize it with a value
There are a few ways to acquire storage for objects:
- You can acquire static, thread static and local storage by defining variables. As an example, the storage for the pointer variable
ptr
was allocated like this - not to be confused with the storage that the pointer points to.
- You can acquire dynamic storage using a(n allocating)
new
expression (or the std::malloc
family of functions from the C standard library).
Neither of these options let you specify the memory address where the storage should be placed. There is no way in standard C++ to request storage for a variable from an arbitrary address.
when I run this code I get a segmentation fault
The reason from perspective of C++: You indirect through a pointer that doesn't point to an object. The behaviour of your program is undefined.
The reason from perspective of your operating system: The process attempted to write into a virtual address that was not mapped, or was marked protected or read only, and so the operating system raised a signal and terminated the process.
Now, if and only if the C++ implementation that you use gives you a guarantee that some arbitrary memory location may be used for storage, then you can use placement-new expression to create an object in that memory location. An example of such situation is mmap
call on a POSIX system. Here is an example how to create an object in such storage:
// let there be storage at some memory address
// let the amount of storage, and alignment of the address be sufficient for T
char* storage = some_special_address;
// create an object into the storage
T* tptr = new(storage) T;
// after you're done using the object, destroy it:
tptr->~T();
// after destruction, the storage can be released, if needed and if possible
How do I do what I am trying to do?
Run your program on a system that doesn't use virtual memory (i.e. on a system that does not have an operating system). Then consult the manual of that system for what memory addresses you can use. Then see the previous example about how to create objects in the storage that you control. Make sure that the address satisfies the alignment requirement of the object that you create.