I have question, in my assignment I have to switch string using pointers.
I done this with use of pointer to pointer.
However, i think this should be done without pointer to pointer
but i can't figure it out how this should be done.
Can I swap address that pointer one is holding with address that pointer 2 holds with
use of temporary pointer?
#include <iostream>
void swap2p(char*& pOne, char*& pTwo); // <- prototype of the function
/*
My function takes reference to a pointer (so in fact address of a pointer) as argument
for 1st and 2nd value
*/
int main() {
char One[]{ "this is Sparta"}; // <- an array of stringchar Two[]{"this is England"}; // <- an array of stringchar* pOne = One; // <- pointer to first array of strings char* pTwo = Two; // <- pointer to second array of strings
std::cout << "One: " << pOne << std::endl; // printing of the original value
std::cout << "Two: " << pTwo << std::endl;
swap2p(pOne, pTwo); // <- magic starts here: I am sending two elements
std::cout << "-------------------------" << std::endl;
std::cout << "One: " << pOne << std::endl; // <- printing after function operation
std::cout << "Two: " << pTwo << std::endl; // <- printing after function operation
system("pause");
return 0;
}
void swap2p(char*& pOne, char*& pTwo) // <- receiving 2 values such as 0x61ff09 and 0x61fef9 (example of memory addresses)
{
char* tmp = pOne; // [b]<- pointer tmp is assigned with address 0x61ff09
pOne = pTwo; pOne is assigned with 0x61fef9
pTwo = tmp; pTwo is assigned with 0x61ff09
}
> My function takes reference to a pointer (so in fact address of a pointer) as argument
> for 1st and 2nd value
It is best to think of a references as an alias to (just another name for) an object.
In void swap2p( char*& arg1, char*& arg2 );, arg1 and arg2 are names using which the objects which were used to initialise the references (objects that were passed by reference) can be accessed.
For this call
1 2 3
char* x = One ;
char* x = Two ;
swap2p( x, y ) ;
arg1 acts as an alis for x and arg2 acts as an alias for y; during this execution of the function, anything done to arg1 is done to x, and anything done with arg2 is done with y.