How to swap between array and pointer c++ - c++

I am trying to swap between array and pointer in c++
My code is as the following :
void foo(int* a, int* b);
void main()
{
int *a = NULL;
int b[6]={2,3,5,6};
foo(a,b);
}
void foo(int* a, int b[])
{
int * c;
c=a;
a=b;
b=c;
}
While I return out from the Method nothing changed ,
within the method everything work fin but when the method return nothing change.
my question is:
A) what is my mistake.?
B) How should I fix it.

Your mistake is that you assume arrays are pointers. They are not. They can decay to pointers.
You can't change b, but you can change a, by passing it by reference:
void foo(int*& a, int b[])
{
int * c;
c=a;
a=b;
}

In your example, b is allocated. But you can't transfer this "being allocated" property of an array to a pointer. You can allocate a pointer (by using malloc or new) but you can't de-allocate an array. So I'm afraid what you want to do isn't possible.
If all you want to do is exchange the contents of a and b, you'll have to do that the hard way (physically copy each value, or memcpy for the whole array at once), but you can't simply change the array in such a way that its address changes to that of a.
(Obligatory remark: since you tagged your question c++, you should use vectors.)

Related

I think this is bad C++ coding ('new' in a function to point to a local variable). Am I correct?

I want to create a class that contains a pointer, and upon initialization, the pointer can be dereferenced to give an integer assigned at initialisation.
This was my first attempt to write this code. This passed compiler and gave me the correct result without warning. However I later think this code has a potential problem.
That is in the constructor, the integer a is created on a stack framed to the constructor function. I am however making 'ptr' pointing to this stack memory address. The problem is this memory can be reused upon maybe calling other functions, so I might get garbage value if I am not lucky.
#include <iostream>
using namespace std;
class P {
public:
int *ptr;
P(int);
};
P::P(int a){
int *ptr = new int (0);
ptr = &a;
}
int main() {
P p(99);
cout <<*(p.ptr) <<endl;
}
A better way would be to create an integer variable on heap, copy the value of a to that variable, and make ptr pointing to that memory space on heap.
P::P(int a){
int *i = new int (0);
*i = a;
ptr = i;
}
Is my analysis correct?
Thanks!
The statements
int *ptr = new int (0);
ptr = &a;
are problematic, but probably not because of the reasons you think.
The reason it's problematic is because you define a new and distinct local variable ptr inside the function. This is not the same as the P::ptr member variable.
There's also a second problem, which is a memory leak. You allocate memory with new, but you never free the memory with delete.
If you really is required to use a raw and non-owning pointer to a single int value, I recommend you do it using a constructor initializer list:
P(int a)
: ptr{ new int(a) }
{
// Empty
}
Here new int(a) will create a new int value and copy the value of a into it.
Remember to then create a destructor which free's the memory you have allocated. And then you need to learn about the rules of three, five and zero.
To use the rule of zero, and to avoid memory leaks and make life simpler, use a smart pointer like std::unique_ptr:
struct P
{
std::unique_ptr<int> ptr;
P(int a)
: ptr{ std::make_unique<int>(a) }
{
}
};
And of course, since it's just about a single int value, and you don't need a reference to the original value, there's no need for pointers at all.

Different passing parameters, different output

If we have the following code, the memory for variable b is not taken, when we call function f. But if the function f would have the prototype void f(int* &a) then the memory would be allocated. How is this possible?
#include <iostream>
using namespace std;
void f(int* a)
{
a = new int[10];
a[0] = 55;
}
int main()
{
int *b;
f(b);
return 0;
}
EDIT:
Well I got the main idea but why is still possible then?
void f(int a[])
{
a[0] = 5;
}
int b[] = {1,2,3,4,5};
f(b);
//The value of b[0] will be 5 after the end of function call
You are passing the pointer by value, so f has its own copy of it. The pointer a is local to f, so the caller has no access to it (and the memory allocated is leaked, BTW).
When you pass the pointer by reference, a is semantically the same pointer as was passed. So the pointer passed by the caller points to the memory allocated in the function.
Pointer int * b; is actually a variable. A variable which hold an memory address of an integer. For example:
int n;
int* b = &n; // pointer b is pointing to n
Since a pointer is a variable you can pass it by value or by reference. Here you pass it by value to the function. Check also the http://en.cppreference.com/w/cpp/language/pointer.
In the case of void f(int* &a) you pass by reference the int* a variable. It is a variable (that hold a memory address of a variable of type int) which it is not initialized to any value yet in your code (in main()).
In your second code. In the function void f(int a[]) when you pass int b[] = {1,2,3,4,5}; with f(b); you make "implicit" conversion of array name to a pointer. The problem is that the function f() does not know the size of the array. For example you use this calls in functions like strlen() where you pass null terminating strings. Check book "The C++ Programming Language", 3rd Edition by Bjarne Stroupstrup page 92.
There is also a basic rule: a[i] <=> (*(a+i)). So your function void f(int a[]) is equal with void f(int* a) definition. Check "Navigating C++ and Object-oriented Design" by Gail Anderson, page 40: http://books.google.gr/books?id=b-NiT6w8FTAC&pg=PA40#v=onepage&q&f=false

How to intepret (const int & a) and new int (a), what does it do?

int * myFun(const int & a)
{
int * c = new int(a);
int b = *c;
return &b;
}
1.How to intepret (const int & a) and new int (a) , what does it do?
2.Could you explain to me why there is a memory leak?
You may want to pick a beginner book from The Definitive C++ Book Guide and List, read it through and then start again.
On to your questions:
const int & a is a const reference to an int, named a. Basically, it means something that points to another int variable somewhere, and behaves just like that int, except you can't change its value
new int (a) means you dynamically allocate memory somewhere on the heap for an int variable, and initialize that variable with the value a. This expression returns the address of the variable you just created
Why is there a memory leak ? You allocate memory with the new int(a) statement, but never release it. This should be done with:
delete c;
before the end of your function.
As noted in the comments, this function has undefined behavior in the return statement, since you return the address of a local variable (You may need to actually read that C++ beginner book to understand what that means).
Judging by the code, you are using c++
You get a new pointer c with the value of a then you make b, with the same value as c, you return b, leaving c as the leak because nothing points to c anymore.
At then end:
a is the const
b is the value of c, which is the value of a
c is a pointer to a new variable that is no longer referenced in your code

Passing pointer to a function in C++

I wrote the following piece of code
#include <iostream>
using namespace std;
void temp (int * x)
{
x=new int [2];
x[0]=1;
x[1]=2;
}
int main()
{
int *ptr;
temp(ptr);
cout<<ptr[0]<<endl;
cout<<ptr[1]<<endl;
return 0;
}
Running it gives seg fault, so is the memory allocation which happens inside temp function local to function? The memory gets deallocated while returning from temp? I know, that to solve this problem, I need to pass pointer to pointer ptr, but still, why exactly does this thing not work?
To alter something in a function in C, you need to pass a pointer to it. In this case, you want to alter a pointer, so you need a pointer to a pointer:
void temp (int** x)
then in the function use *x where you now have x (you will need (*x)[n], as *x[n] means something else)
Then call temp with:
temp(&ptr);
This should solve it in C, and will work in C++.
In C++, you could also pass a reference to a pointer:
void temp(int*&x)
which will allow the syntax you have already to be used unchanged.
Think about this code
void temp(int x)
{
x = 2;
}
int main()
{
int y = 3;
temp(y);
cout << y << '\n';
}
What the output going to be 2 or 3? Of course it's three. Now what's the difference between this and your example? Nothing at all. Unless you use a reference everything in C++ is passed by value. x is a copy of y, so changes to x never affect y. This is true whetever the types involved, its true of ints and its true of pointers.
C++ answer:
You are passing the int* argument into temp by value. This means that you are copying ptr into the function, and the pointer x is a completely separate object. You then assign the result of new int[2] to this copy, but the ptr in main is left unaffected. To be able to modify the pointer passed as an argument, you need to take it by reference:
void temp (int*& x)
{
// ...
}
This means that x now refers to the pointer that is passed as an argument. The alternative solution here is to return an int* instead:
int* temp()
{
int* x = new int [2];
x[0]=1;
x[1]=2;
return x;
}
int main()
{
int *ptr = temp();
// ...
}
However, the caller of temp might be unclear about the ownership of the int object. They need to delete[] it, but this isn't made explicit in the interface. Instead, you can return a std::unique_ptr.
int *ptr;
You created an automatic variable here and you passed it to
temp(ptr);
This is pass by copy so x will get the value of ptr and x scope is within the temp function. It is an automatic variable in that scope.When you return from temp its value is lost.
Now, the memory allocated and pointed to by x is in no way reflected to ptr in main. (They are not connected)
You need to do temp(int*& ptr) i.e. pass by reference. Or temp(int** ptr) i.e. pass by address
Note: You have a memory leak in your temp
You need to pass a ** because you are allocating x inside of your function.

passing array on the heap and on the stack to function

I have a simple c++ question concerning passing an array to a function foo(). Assume I have two arrays A and B:
double* A=new double[3];
and
double B[3];
When I pass both to the function
foo(double* A; double *B)
which is intended to manipulates both arrays. However by executing
foo(A,B)
foo is acting on a copy of A and only the changes to B remain when leaving foo().
This is not the case if foo is defined as
foo(double* &A; double *B).
My question: Why is a copy of a created although I pass the address of A like double* A (as in the case of B) in the first example of foo()?
foo is acting on a copy of A and only the changes to B remain when leaving foo().
What exactly are you doing inside of foo? Changes to the objects themself should be visible outside of foo in both cases. If you are trying to change the value of pointer A, it won't be visible outside of foo - a copy of the pointer is passed to the function, but of course it still points to the same array.
If you want to pass an array reference to a function you have to use a double pointer reference:
foo(double** A, double **B);
double** A=new complex<double>[3];