Difference between T* and T*& C++ - c++

What is the difference between the two copy functions below? I do not seem to see a difference between them. Specifically the void*& vs the void*.
So what is the difference between T*& and T*? When would I use one over the other? Also, if I made them accept const parameters, what would happen? What would the difference be?
#include <iostream>
void Copy(void* Source, void* Destination, int Size)
{
//memcpy(Destination, Source, Size);
char* S = static_cast<char*>(Source);
char* D = static_cast<char*>(Destination);
*D = *S;
}
void Copy2(void* &Source, void* &Destination, int Size)
{
char* S = static_cast<char*>(Source);
char* D = static_cast<char*>(Destination);
*D = *S;
}
int main()
{
int A = 2;
int B = 5;
int C = 7;
void* pA = &A;
void* pB = &B;
void* pC = &C;
Copy(pA, pB, 1);
Copy2(pA, pC, 1);
std::cout<< B <<std::endl;
std::cout<< C <<std::endl;
}
Both of the above print "2". Both are the same no?

One is a pointer, the other is a reference to a pointer.
Google both and pick up a C++ basics book.
Think of passing by pointer as passing a memory address by value (ie, a copy). In the receiving function, you have a copy of the memory address and you can change where that memory address pointer points to, and what that destination memory contents looks like. When you return from that function, the destination memory is still changed, but the original pointer is unchanged.
In contrast, a reference to a pointer allows you to change where that memory points to after you return from the function. Otherwise it is the same.
A common usage is a funciton which allocates memory such as:
SomeClass *someClass = null;
PopulateSomeClass(someClass);
...
void PopulateSomeClass(SomeCLass* &someCLass)
{
someClass = new SomeClass;
}
But really, google this for more detail - this is a more basic C++ concept.
For instance, a reference is typically implemented as a const * under the covers in the compiler. So it is a const pointer to pointer.

Related

Write Access Violation (ptr was nullptr) while returning a pointer in a function that was used to create a dynamic array [duplicate]

I have my function and I am filling targetBubble there, but it is not filled after calling this function, but I know it was filled in this function because I have there output code.
bool clickOnBubble(sf::Vector2i & mousePos, std::vector<Bubble *> bubbles, Bubble * targetBubble) {
targetBubble = bubbles[i];
}
And I am passing the pointer like this
Bubble * targetBubble = NULL;
clickOnBubble(mousePos, bubbles, targetBubble);
Why it is not working?
Because you are passing a copy of pointer. To change the pointer you need something like this:
void foo(int **ptr) //pointer to pointer
{
*ptr = new int[10]; //just for example, use RAII in a real world
}
or
void bar(int *& ptr) //reference to pointer (a bit confusing look)
{
ptr = new int[10];
}
You are passing the pointer by value.
Pass a reference to the pointer if you want it updated.
bool clickOnBubble(sf::Vector2i& mousePos, std::vector<Bubble *> bubbles, Bubble *& t)
if you write
int b = 0;
foo(b);
int foo(int a)
{
a = 1;
}
you do not change 'b' because a is a copy of b
if you want to change b you would need to pass the address of b
int b = 0;
foo(&b);
int foo(int *a)
{
*a = 1;
}
same goes for pointers:
int* b = 0;
foo(b);
int foo(int* a)
{
a = malloc(10); // here you are just changing
// what the copy of b is pointing to,
// not what b is pointing to
}
so to change where b points to pass the address:
int* b = 0;
foo(&b);
int foo(int** a)
{
*a = 1; // here you changing what b is pointing to
}
hth
You cannot change the pointer unless you pass it by (non const) reference or as a double pointer. Passing by value makes a copy of the object and any changes to the object are made to the copy, not the object. You can change the object that the pointer points to, but not the pointer itself if you pass by value.
Have a read of this question to help understand the differences in more detail When to pass by reference and when to pass by pointer in C++?

Function with pointer as parameter - what does the function expect by calling?

I saw this example:
void pass_by_value(int* p)
{
//Allocate memory for int and store the address in p
p = new int;
}
void pass_by_reference(int*& p)
{
p = new int;
}
int main()
{
int* p1 = NULL;
int* p2 = NULL;
pass_by_value(p1); //p1 will still be NULL after this call
pass_by_reference(p2); //p2 's value is changed to point to the newly allocate memory
return 0;
}
if i call the function pass-by-value, shouldnt it expect something like "&p" instead of p?
The pass-by-value is messed up anyway, the value passed to the function would be lost when the call completes and the memory would leak. It's legal code, it's just useless. If not using references or function return value the function would need to take a pointer-to-pointer (really, the compiler is likely to produce the same code for both the pointer-to-pointer and reference-to-pointer cases - barring inlining - it's just a bit cleaner to use the reference):
void foo(int ** p)
{
*p = new int;
}
int main()
{
int * p = nullptr;
foo(&p);
delete p;
}

Copying "this" pointer to a buffer

I need to copy the address of this pointer to a buffer and re-typecast it elsewhere. I am aware that I can do it, if I do it outside the class. But,here I specifically need to use some member function as given in the sample code provided here:
#include <iostream>
#include <cstring>
class MyClass
{
public:
MyClass(const int & i)
{
id = i;
}
~MyClass()
{
}
void getAddress(char* address)
{
memcpy(address, this, sizeof(this));
}
void print() const
{
std::cout<<" My id: "<<id<<std::endl;
}
private:
int id;
};
int main()
{
MyClass myClass(100);
std::cout<<"myClass: "<<&myClass<<std::endl;
myClass.print();
// Need to copy the address to a buffer, sepcifically using a function as follows and retrieve it later
char tmp[128];
myClass.getAddress(tmp);
// retreiving the pointer
MyClass* myClassPtr = (MyClass*) tmp;
std::cout<<"myClassPtr: "<<myClassPtr<<std::endl;
myClassPtr->print();
return 0;
}
My Output:
myClass: 0x7fff22d369e0
My id: 100
myClassPtr: 0x7fff22d369f0
My id: 100
As we can see two addresses are different. However, both function are printing the id correctly. I wonder how this happens! I also need the correct method.
Correct version of getAddress():
void getAddress(char* address)
{
const MyClass* tmp = this;
memcpy(address, &tmp, sizeof(this));
}
Update:
// retreiving the pointer
// MyClass* myClassPtr = (MyClass*) tmp; - wrong
MyClass* myClassPtr = *( (MyClass**) tmp );
You are not copying the value of the this pointer, but the data that the pointer is pointing to (memcpy expects the address of the data to copy).
The correct syntax would be:
MyClass* ptr = this;
memcpy(address, &ptr, sizeof(ptr));
That is why you get the same/correct output at the end.
Then, the assignment
MyClass* myClassPtr = (MyClass*) tmp;
is wrong too, you set the pointer to the same address as the char buffer, not to the address that is stored in the char buffer.
A possible solution could look like this:
MyClass* myClassPtr;
memcpy( &myClassPtr, tmp, sizeof( MyClass*));
Finally: I'd like to know what exactly you want to do, that you want to implement something like this? Maybe this is the solution for this problem, but I have a strong feeling that this is the wrong solution for the real problem ...

C++ Understanding Pointer Passing and Scope [duplicate]

I have my function and I am filling targetBubble there, but it is not filled after calling this function, but I know it was filled in this function because I have there output code.
bool clickOnBubble(sf::Vector2i & mousePos, std::vector<Bubble *> bubbles, Bubble * targetBubble) {
targetBubble = bubbles[i];
}
And I am passing the pointer like this
Bubble * targetBubble = NULL;
clickOnBubble(mousePos, bubbles, targetBubble);
Why it is not working?
Because you are passing a copy of pointer. To change the pointer you need something like this:
void foo(int **ptr) //pointer to pointer
{
*ptr = new int[10]; //just for example, use RAII in a real world
}
or
void bar(int *& ptr) //reference to pointer (a bit confusing look)
{
ptr = new int[10];
}
You are passing the pointer by value.
Pass a reference to the pointer if you want it updated.
bool clickOnBubble(sf::Vector2i& mousePos, std::vector<Bubble *> bubbles, Bubble *& t)
if you write
int b = 0;
foo(b);
int foo(int a)
{
a = 1;
}
you do not change 'b' because a is a copy of b
if you want to change b you would need to pass the address of b
int b = 0;
foo(&b);
int foo(int *a)
{
*a = 1;
}
same goes for pointers:
int* b = 0;
foo(b);
int foo(int* a)
{
a = malloc(10); // here you are just changing
// what the copy of b is pointing to,
// not what b is pointing to
}
so to change where b points to pass the address:
int* b = 0;
foo(&b);
int foo(int** a)
{
*a = 1; // here you changing what b is pointing to
}
hth
You cannot change the pointer unless you pass it by (non const) reference or as a double pointer. Passing by value makes a copy of the object and any changes to the object are made to the copy, not the object. You can change the object that the pointer points to, but not the pointer itself if you pass by value.
Have a read of this question to help understand the differences in more detail When to pass by reference and when to pass by pointer in C++?

Is it passing by pointer?

void func(char* buf) { buf++;}
Should I call it passing by pointer or just passing by value(with the value being pointer type)? Would the original pointer passed in be altered in this case?
This is passing by value.
void func( char * b )
{
b = new char[4];
}
int main()
{
char* buf = 0;
func( buf );
delete buf;
return 0;
}
buf will still be 0 after the call to func and the newed memory will leak.
When you pass a pointer by value you can alter what the pointer points to not the pointer itself.
The right way to do the above stuff would be
ALTERNATIVE 1
void func( char *& b )
{
b = new char[4];
}
int main()
{
char* buf = 0;
func( buf );
delete buf;
return 0;
}
Notice the pointer is passed by reference and not value.
ALTERNATIVE 2
Another alternative is to pass a pointer to a pointer like
void func( char ** b )
{
*b = new char[4];
}
int main()
{
char* buf = 0;
func( &buf );
delete buf;
return 0;
}
Please note I am not in any way advocating the use of naked pointers and manual memory management like above but merely illustrating passing pointer. The C++ way would be to use a std::string or std::vector<char> instead.
The pointer will not be altered. Pass by pointer means pass an address. If you want the pointer altered, you have to pass a double pointer a deference it once.
foo( char **b)
{
*b = NULL;
}
The pointer itself is being passed by value (the memory being pointed at is being passed by pointer). Changing the parameter inside the function will not affect the pointer that was passed in.
To implement reference semantics via "passing a pointer", two things must happen: The caller must take the "address-of" the thing to be passed, and the callee must dereference a pointer.
Parts of this can be obscured by the use of arrays, which decay to a pointer to the first element - in that sense, the array content is always "passed by reference". You can use an "array-of-one" to obscure the dereferencing, though.
This is the straight-forward apporoach:
void increment_me(int * n) { ++*n; } // note the dereference
int main() { int n; increment_me(&n); } // note the address-of
Here's the same in disguise:
void increment_me(int n[]) { ++n[0]; } // no visible *
int main() { int n[1]; increment_me(n); } // or &