int main()
{
int x = 2, y = 4;
func(&x, &y);
printf("%d %d\n", x, y);
return 0;
}
void func(int *x, int *y)
{
int *temp;
temp = x;
x = y;
y = x;
}
Hi
For this code i have no idea why the output is 2 4 instead of 4 4. Since x = y in func() means x now points to the address of y, and y = x in func() means y now points to the address of x (which is y), both variables are now pointing to y already.
Many thanks!
The answer is simple: You change the pointer values inside func - but not the values they point at. I guess you'd like to swap the variables (due to the temp var).
This code should work (swapping values):
void func(int *x, int *y)
{
int temp = *x; // dereferencing the pointer to get the value it points at.
*x = *y;
*y = temp;
}
Too keep your initial expectations (which don't make any sense code wise due to the second assignment):
void func(int *x, int *y)
{
*x = *y;
*y = *x;
}
Nope, func() will receive copies of those addresses and this won't affect the variables outside the function - all changes done to variables local to func() will be discarded once func() exits.
You are just temporarily assigning the address of 'x' to the address of 'y' within func. In order to make the assignment, you need to dereference your pointers.
*x = *y;
*y = *x;
Try this
#include <iostream>
using namespace std;
void func(int *x, int *y);
int main()
{
int x = 2, y = 4;
func(&x, &y);
//printf("%d %d\n", x, y);
cout << "X - " << x << endl;
cout << "Y - " << y << endl;
return 0;
}
void func(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
You're making copies of the passed in pointers, they are local to your function. Any change you make to them doesn't affect the outside. You should capture the pointers by reference &.
void func(int*& x, int*& y){
// as before...
}
Now the changes inside the function will be correctly reflected outside of it. On problem remains though. You're passing in the address of local variables, and attempt to change their pointers - that doesn't work. When you take the address of a variable &x, you make a new temporary pointer, which can't be converted to a reference-to-pointer.
Do this instead:
int main(){
int x = 2, y = 4;
int *px = &x, *py = &y;
func(px, py);
printf("%d %d\n",*px,*py);
}
Edit: If you instead want to swap / set the values of x and y and not just some pointers, do as the other answers state.
The problem is that you're trying to write your own version of std::swap. This will work:
int x = 2, y = 4;
std::swap(&x, &y);
printf("%d %d\n", x, y);
return 0;
Related
I am getting an illegal hardware instruction error when compiled on mac. Appreciate any pointers.
#include<iostream>
using namespace std;
int * fun(int * x)
{
return x;
}
int main()
{
int * x;
*x=10;
cout << fun(x);
return 0;
}
Pointers are just pointers. In your code there is no integer that you could assign a value to.
This
int * x;
Declares x to be a pointer to int. It is uninitialized. It does not point anywhere. In the next line:
*x=10;
You are saying: Go to the memory that x points to and assign a 10 to that int. See the problem? There is no int where x points to, because x doesnt point anywhere. Your code has undefined behavior. Output could be anything.
If you want to assign 10 to an int you need an int first. For example:
#include<iostream>
using namespace std;
int * fun(int * x)
{
return x;
}
int main()
{
int y = 0;
int * x = &y;
*x=10;
cout << fun(x);
return 0;
}
This assigns 10 to y. The cout is still printing the value of x, which is the adress of y. It does not print the value of y. Not sure what you actually wanted.
The problem is that in your program the pointer x is not pointing to any int variable. So first you have to make sure that the pointer x points to an int object as shown below.
You can sovle this as shown below:
int i = 0; //create the int object to which x will point
int *x = &i; //make x point to variable i
*x = 10; //dereference the pointer x and assign 10 to the underlying variable i
cout << *fun(x); //this prints 10
It's been a while since I've coded anything in C++. While I was trying to help another person as a CIS Tutor, he wanted to know why it's necessary to have an ampersand next to a pointer to an int.
I figured that if you were to pass a pointer by reference and you point to something else, the main knows after you passed that val will equal to whatever you set it equal to.
There will be an example below will demonstrate what I'm trying to say.
Is this correct?
//main function
int variable = 0;
int* val = &variable;
function1(val);
cout << *val << endl;
function2(val);
cout << *val << endl;
//Passing in a pointer with reference.
void function1(int*& value)
{
int variable = 9;
value = &variable;
}
//Passing in a pointer without reference.
void function2(int* val)
{
int variable = 9;
value = &variable;
}
My assumption is that the program will output 9 instead of 8 or 0. I hope this give you guys a clear picture of what I'm trying to ask.
The difference between passing the values and passing the reference is the same with pointers as with other values (actually pointers are nothing special they just hold numbers that sometimes are adresses of other objects).
With int:
void foo(int x) { x = 1; }
void bar(int& x) { x = 2; }
int main() {
int y = 5;
foo(y);
std::cout << y; // prints 5
bar(y);
std::cout << y; // prints 2
}
Now with pointers:
void foo(int* x) { x = 0; }
void bar(int*& x) { x = 0; }
int main() {
int y = 42;
int* z = &y;
foo(z);
std::cout << z; // prints the address of y
bar(z);
std::cout << z; // prints 0
}
Note that your function1 is broken, because when you call it
int* y;
function1(y);
std::cout << *y; // **baaam**
// the value y points to is already gone
the int inside the function ends its lifetime when the function returns and the caller cannot use the value in any meaningful way. Note that in this particular example you would probably get the "correct" value printed, but that is just by coincidence and dereferencing y after passing it to function1 is undefined behaviour.
I keep getting the error message, exc_bad_access code=1 for my line
asize = *(***(y) + **(y + 1));
in the summation function. I dont quite understand what to do with this error, but i know that it is not a memory leak.
I am trying to get the values stored in the y pointer array, add them, and store it in the variable asize.
void allocArr (int **&x, int ***&y, int **&q, int ****&z)
{
x = new int *[2];
y = new int **(&*x);
q = &*x;
z = new int ***(&q);
}
void putArr(int **&x, int &size1, int &size2)
{
*(x) = *new int* [size1];
*(x + 1) = *new int* [size2];
}
void Input (int **&x, int *&arr, int &size1,int &size2, int a, int b)
{
cout << "Please enter 2 non-negative integer values: "<< endl;
checkVal(size1, a);
checkVal(size2, b);
putArr(x, size1, size2);
arr[0] = size1;
arr[1] = size2;
cout << x[0];
}
void summation(int ***&y, int *&arr)
{
int asize = 0;
asize = *(***(y) + **(y + 1));
**y[2] = *new int [asize];
*(arr + 2) = asize;
}
int main()
{
int size1, size2;
int a = 1, b = 2;
int** x;
int*** y;
int** q;
int**** z;
int *arr = new int [2];
allocArr(x, y, q, z);
Input(x, arr, size1, size2, a, b);
summation(y, arr);
display(z);
}
Thank you for the help. Im really struggling here...
Not sure how you got started with the code. The code can be simplified quite a bit to help you, and readers of your code, understand what's going on.
Function allocArr
The lines
y = new int **(&*x);
q = &*x;
can be
y = new int **(x); // &*x == x
q = x;
Function putArr
You have the function declaration as:
void putArr(int **&x, int &size1, int &size2)
It can be changed to:
void putArr(int **x, int size1, int size2)
without changing how you are using the variables.
Your code in the function seems strange. Did you mean for x[0] and x[1] to point to an array of size1 and size2 ints, respectively? If you did, the code would be:
x[0] = new int[size1];
x[1] = new int[size2];
If you don't mean the above, it's hard to figure out what you are trying to do with your code.
Function Input
You have the function declaration as:
void Input (int **&x, int *&arr, int &size1,int &size2, int a, int b)
It can be changed to:
void Input (int **x, int *arr, int &size1,int &size2, int a, int b)
without changing how you are using the variables.
You are calling a function checkVal, but your posted code doesn't have that function. It's not clear what that function is doing. You have the line
cout << "Please enter 2 non-negative integer values: "<< endl;
just before the calls to checkVal. Presumably, checkVal reads the input and stores them in size1 in the first call and size2 in the second call. It's not clear how the second argument to checkVal is used.
And then, you have the line:
cout << x[0];
It's not clear what you wish to accomplish from printing an int* to cout. Perhaps it was part of your debugging code. The line doesn't change anything else in the program. It's just strange to see it there.
Function summation
You have the function declaration as:
void summation(int ***&y, int *&arr)
It can be changed to:
void summation(int ***y, int *arr)
without changing how you are using the variables.
In this function, you have the expression:
asize = *(***(y) + **(y + 1));
What do you get when you evaluate ***(y)?
***(y) = **(*y) = **(x) = *(*x) = *(x[0]) = uninitialized value from the line:
x[0] = new int[size1];
You will get unpredictable behavior when you use an uninitialized value.
The second term of the line, **(y + 1) is the worse culprit.
You allocated memory for y as:
y = new int **(&*x);
It's a pointer to a single object of type int**, not an array. y+1 is not a valid pointer. Dereferencing (y+1) leads to undefined behavior. In your case, you are seeing exc_bad_access, which makes sense now since you are accessing memory that is out of bounds.
Since I don't know what you are trying to compute in that expression, it's hard for me to suggest something useful. I hope you have enough to take it from here.
Can someone demonstrate how to pass by pointers using one function that takes two arguments from two variables as input?
#include <iostream>
using namespace std;
int passPoints(int *x, int *y)
{
int y = *x * *y;
return(y);
}
int *X, *Y;
int main()
{
cout<<"enter two values: ";
cin>>*X;
cin>>*Y;
cout<<"RESULT = "<<passPoints(X,Y);
return 0;
}
Having trouble.
Like this:
int X, Y;
int main()
{
cout<<"enter two values: ";
cin>>X;
cin>>Y;
cout<<"RESULT = "<<passPoints(&X,&Y);
return 0;
}
The biggest problem in your code (if it is not a typo when you are extracting for question) is, int* X and Y are null pointer and the location they are pointing at are not valid for you to update. You need to make sure that these pointers are pointing to a valid memory location, either by:
int x, y;
int* xPtr = &x;
int* yPtr = &y;
passPoints(xPtr, yPtr);
or simply
int x, y;
passPoints(&x, &y);
now the pointers received by passPoints() are valid pointers
So I'm trying to familiarise myself with c++ pointers by running the following code.
#include <iostream>
using namespace std;
int main(void){
int* x;
cout << &x << endl;
return 0;
}
which works fine and prints the pointer value of x but
#include <iostream>
using namespace std;
int main(void){
int* x;
*x = 100;
cout << &x << endl;
return 0;
}
gives me a segmentation fault when I try to tun it. Why is this? I don't see how that extra line should change anything about the address of x.
You did not allocate an object which you are going to assign.
int* x;
The value of x is unspecified and can be any arbitrary value. So the next statement
*x = 100;
is invalid.
You have to write
x = new int;
*x = 100;
Or
x = new int( 100 );
Or even
x = new int { 100 };
provided that your compiler supports the list initialization for operator new which was introduced in the C++ 2011..
and prints the pointer value of x but
Not exactly.
std::cout << &x; it prints x's address (the pointer's address);
std::cout << x; prints the address, x points to;
std::cout << *x; prints what x points to;
int* x;
*x = 100;
Here, x is just a pointer, you need to allocate memory for the 100. For example
int* x = new int;
*x = 100;
std::cout << *x;
Or just
int* x = new int( 100 );
std::cout << *x;
Without allocating memory and leaving x uninitialized, by *x = 100 you're trying to change some random memory, which leads to undefined behavior.
You have undefined behaviour.
Your first example is fine since &x (which has type int**) is the address of a stack allocated pointer. One of the << overloads in cout is defined to output that correctly.
In the second example, you are dereferencing a pointer that is not pointing to anything. That's undefined behaviour; hence the crash. If you'd written
int y;
int* x;
x = &y;
*x = 100; /*this means that y is now 100*/
then all would have been well since now x is pointing to something.