This is what i have:
void g(int *&x) {
int a = 3;
x = &a;
}
void h(const int *&x) {
int b = 2;
x = &b;
}
int main() {
int *p = new int;
*p = 5;
g(p);
cout << p << " " << *p << endl; // Print #2
cout << p << " " << *p << endl; // Print #3
const int*p1 = p;
h(p1);
cout << p << " " << *p << endl; // Print #4
cout << p << " " << *p << endl; // Print #5
}
From what i understand, Print#2 and Print#3 should have the same result but it isn't when i compile it. It goes for Print#4andPrint#5 too. Can someone help me?
Updated : This is the output looks like when i compiled it on my computer:
00EFF9D4 3 //1
00EFF9D4 1552276352 //2
00EFF9D4 2 //3
00EFF9D4 1552276352 //4
shouldn't (1) and (2) be the same ? (3) and (4) either.
I assume you mean int a in g().
Your function make the pointer point to a local variable, which after the termination of the function, will go out of scope.
You then dereference the pointer, which invokes Undefined Behavior.
Related
Let's consider I have the following x pointer variable in my function:
int* x = new int { 666 };
I know I can print its value by using the * operator:
std::cout << *x << std::endl;
And that I can even print the address of where the 666 is being stored on the heap, like this:
std::cout << (uint64_t)x << std::endl;
But what I'd like to know is on whether it's also possible to grab the address of the x variable itself, that is, the address of the region of memory in the stack containing the pointer to the heap int containing 666?
Thanks
Just use another &
std::cout << (uint64_t)&x << std::endl;
e.g.:
int v = 666; // variable
int * x = &v; // address of variable
int ** p = &x; // address of pointer x
and so on
int *** pp = &p;
int **** ppp = &pp;
and how to access to it:
std::cout << ****ppp << " == " << ***pp << " == "
<< **p << " == " << *x << " == " << v << std::endl;
Considere the following code in c++:
#include <iostream>
using namespace std;
int main() {
int x=2, y;
int *p = &x;
int **q = &p;
std::cout << p << std::endl;
std::cout << q << std::endl;
std::cout << *p << std::endl;
std::cout << x << std::endl;
std::cout << *q << std::endl;
*p = 8;
*q = &y;
std::cout << "--------------" << std::endl;
std::cout << p << std::endl;
std::cout << q << std::endl;
std::cout << *p << std::endl;
std::cout << x << std::endl;
std::cout << *q << std::endl;
return 0;
}
The output of code is (of course the list numbers is not the part of output):
0x7fff568e52e0
0x7fff568e52e8
2
2
0x7fff568e52e0
'-----------'
0x7fff568e52e4
0x7fff568e52e8
0
8
0x7fff568e52e4
Except for 7 and 9, all outputs were expected for me. I appreciate someone explaining them to me.
The variable y was not initialized
int x=2, y;
So it has an indeterminate value.
As the pointer q points to the pointer p
int **q = &p;
then dereferencing the pointer q you get a reference to the pointer p.
So this assignment statement
*q = &y;
in fact is equivalent to
p = &y;
That is after the assignment the pointer p contains the address of the variable y.
So this call
std::cout << p << std::endl;
now outputs the address of the variable y.
0x7fff568e52e4
and this call
std::cout << *p << std::endl;
outputs the indeterminate value of y that happily is equal to 0.
9. 0
I have piece of code here.
void MyString::rm_left_space(char *s){
int size = getSize(s);
char s2[size];
char *s1=&s2[0];
int i=0;
while(*(s+i)==' '){
i++;
}
for (int k=i,l=0; k<size; k++) {//start from i, discarding spaces
*(s1+l) = *(s+k);
l++;
}
s=s1;
}
void MyString::rm_right_space(char *s){
int countSpacesfromLast=0;
int size = getSize(s);
int j=size-1;
while(*(s+j)==' '){
countSpacesfromLast++;
j--;
}
char *s2=new char[size-countSpacesfromLast];
for (int t=0; t<size-countSpacesfromLast; t++) {
*(s2+t)=*(s+t);
}
s=s2;
}
void MyString::rm_space(char *s){
rm_left_space(s);
rm_right_space(s);
}
Where there is s=s1 and s=s2 assignment does not happen. How come pointer assignment is not working.
In rm_space method s is unchanged after function calls. Why?
In rm_space method s is unchanged after function calls. Why?
Because s is passed by value. In other words - it's not the variable s that is passed but the value that s holds. The variable s in the called function and the variable s in the calling function are two different variables. Consequently, changes made to one of them does not change the other.
If you want to change s in the calling function inside the called function, you need to use call-by-reference.
Something like:
void MyString::rm_left_space(char*& s){
However, notice that your code have a major problem as it seems you are trying to assign s2 in the called function to s in the calling function. You should never do that as s2 goes out of scope as soon as the function returns.
Example: Difference between pass-by-value and between pass-by-value
This simple program uses pass-by-value
#include <iostream>
void foo(int x)
{
x = 42;
std::cout << "Inside foo: x=" << x << std::endl;
}
int main()
{
int x = 21;
std::cout << "Before foo: x=" << x << std::endl;
foo(x);
std::cout << "After foo: x=" << x << std::endl;
return 0;
}
The output is
Before foo: x=21
Inside foo: x=42
After foo: x=21 // notice x didn't change
because x in foo and in main are two different variables.
This simple program uses pass-by-reference
#include <iostream>
void foo(int& x) // Notice the &
{
x = 42;
std::cout << "Inside foo: x=" << x << std::endl;
}
int main()
{
int x = 21;
std::cout << "Before foo: x=" << x << std::endl;
foo(x);
std::cout << "After foo: x=" << x << std::endl;
return 0;
}
The output is
Before foo: x=21
Inside foo: x=42
After foo: x=42 // notice that x changed
because now x inside foo is a reference to x in main
These examples used int but exactly the same applies for pointers.
Example: Using pointers
#include <iostream>
int x = 21;
int y = 5;
void foo(int* p)
{
*p = 42;
p = &y;
std::cout << "Inside foo: p = " << p << std::endl;
std::cout << "Inside foo: *p = " << *p << std::endl;
}
int main()
{
int* p = &x;
printf("%p\n", (void*)p);
std::cout << "Before foo: p = " << p << std::endl;
std::cout << "Before foo: *p = " << *p << std::endl;
foo(p);
std::cout << "After foo : p = " << p << std::endl;
std::cout << "After foo : *p = " << *p << std::endl;
return 0;
}
Output:
Before foo: p = 0x60106c
Before foo: *p = 21
Inside foo: p = 0x601070
Inside foo: *p = 5
After foo : p = 0x60106c // Pointer value did NOT change
After foo : *p = 42 // Pointed to value DID change
Replacing
void foo(int* p)
with
void foo(int*& p)
will give:
Before foo: p = 0x60106c
Before foo: *p = 21
Inside foo: p = 0x601070
Inside foo: *p = 5
After foo : p = 0x601070 // Pointer value DID change
After foo : *p = 5 // Consequently, the pointed to value also changed
I am new to StackOverflow, if there's any mistake, please Kindly judge me
I am not sure that whether I was misunderstand what you mean, so if there's any misunderstanding, please let me know.
I guess you want to do remove left space in a string, right?
e.g.
" Hello" --> "Hello"
if so, here is my version
#include <iostream>
using namespace std;
#define SIZE 7
void rm_left_space(char* s){
int size = SIZE; //Because I don't know how to getSize, so I use fixed size instead
char s2[size];
char *s1 = &s2[0];
int i = 0;
while(*(s+i) == ' '){
i++;
}
cout << i << endl;
for (int k=i,l=0; k<size; k++) {//start from i, discarding spaces
*(s1+l) = *(s+k);
l++;
}
s=s1; // <-- Shallow copy
}
void rm_left_space_2(char* s){
int size = SIZE;
char *s2 = new char[SIZE]; <-- you should use dynamic array instead of static array
int space_num = 0;
while(*(s+space_num) == ' '){
space_num++;
}
for (int i = 0; i < SIZE; i++){
s2[i] = s[(i + space_num)%size];
}
// s = s2; // <--- shallow copy
for (int i = 0; i < SIZE; i++){ // You should copy whole array
s[i] = s2[i];
}
}
int main(){
char s[] = " hello";
cout << s << endl;
rm_left_space_2(s);
cout << s << endl;
return 0;
}
The output:
hello
hello
Also, you could check the post,
static array vs dynamic array in C++
This question already has answers here:
How to print function pointers with cout?
(7 answers)
Closed 9 years ago.
I'm not clear on what the values that are being returning from calling:
&next, fp, *fp, &return_func_ptr, fp_ptr, &fp_ptr, *fp_ptr
They all seem to give me the value 1. What does it mean?
Also, how would I declare
int (*return_f())(char)
to receive a parameter without using typedef?
#include <iostream>
int next(int n){
return n+99;
}
// returns pointer to a function
typedef int (*fptr)(int); // using typdef
fptr return_func_ptr(){
return next;
}
int f(char){
return 0;
}
int (*return_f())(char){ // how do you pass a parameter here?
// std::cout << "do something with " << param << std::endl;
return f;
}
int main()
{
int x = 5;
// p points to x
int *p = &x;
std::cout << "x=" << x << std::endl; // 5, value of x
std::cout << "&x=" << &x << std::endl; // 0x7fff6447a82c, address of x
std::cout << "p=" << p << std::endl; // 0x7fff6447a82c, value of p is address of x
std::cout << "*p=" << *p << std::endl; // 5, value of x (p dereferenced)
std::cout << "&p=" << &p << std::endl; // 0x7fff6447a820, address of p pointer
// change value of x thru p
// p = 6; // error, can't set int* to int
*p = 6;
std::cout << "x=" << x << std::endl; // 6
int y = 2;
// int *q = y; // error can't initiate with type int, needs int*
// pointer to a function
int (*fp)(int);
std::cout << "&fp=" << &fp << std::endl; // 0x7fff66da6810, address of pointer fp
std::cout << "fp=" << fp << std::endl; // 0, value of pointer fp
fp = &next; // fp points to function next(int)
fp = next;
std::cout << "&next=" << &next << std::endl; // 1, address of function?
std::cout << "fp=" << fp << std::endl; // 1, value is address of function?
std::cout << "&fp=" << &fp << std::endl; // 0x7fff66da6810, address of pointer fp?
std::cout << "*fp=" << *fp << std::endl; // 1, address of function?
// calling function thru pointer
int i = 0;
i = (*fp)(i);
std::cout << "i=" << i << std::endl; // 99
i = fp(i);
std::cout << "i=" << i << std::endl; // 198
// function returns pointer to function
fptr fp_ptr = return_func_ptr();
std::cout << "&return_func_ptr=" << &return_func_ptr << std::endl; // 1
std::cout << "fp_ptr=" << *fp_ptr << std::endl; // 1
std::cout << "&fp_ptr=" << *fp_ptr << std::endl; // 1
std::cout << "*fp_ptr=" << *fp_ptr << std::endl; // 1
int j = fp_ptr(1);
std::cout << "j=" << j << std::endl; // 100
}
There is some pointer here who seems not clear :
// pointer to a function
int (*fp)(int);
std::cout << "&fp=" << &fp << std::endl; // 0x7fff66da6810, address of pointer fp
std::cout << "fp=" << fp << std::endl; // 0, value of pointer fp
Here fp is undefined. Those lines have an undefined behaviour.
After that :
// function returns pointer to function
fptr fp_ptr = return_func_ptr();
std::cout << "&return_func_ptr=" << &return_func_ptr << std::endl; // 1
std::cout << "fp_ptr=" << *fp_ptr << std::endl; // 1
std::cout << "&fp_ptr=" << *fp_ptr << std::endl; // 1
// ^^^^^^^^^^ ^^^^^^^
std::cout << "*fp_ptr=" << *fp_ptr << std::endl; // 1
There are two things here :
On the line I pointed, I'm not sure it is what you wanted to test.
Also, cout doesn't have an overload to take a function pointer, it will take a bool instead. So it should be :
std::cout << "fn_ptr=" << reinterpret_cast<void*>( fn_ptr ) << std::endl;
I would suggest you to read this article about function pointer, it explains almost all you need to know : http://www.learncpp.com/cpp-tutorial/78-function-pointers/
std::cout << "fp_ptr=" << *fp_ptr << std::endl;
should be
std::cout << "fp_ptr=" << (void*)fp_ptr << std::endl;
The cout operator doesn't have an overload for a function pointer, so it uses bool instead. That's why you always get 1 as output. When I compile your code, I even get a warning for that, telling me that it will always evaluate to true. You should switch on all warnings and try to get rid of them.
I'm working on a function to swap pointers and I can't figure out why this isn't working. When I print out r and s in the swap function the values are swapped, which leads me to believe I'm manipulating a copy of which I don't understand because I pass by reference of p and q.
void swap(int *r, int *s)
{
int *pSwap = r;
r = s;
s = pSwap;
return;
}
int main()
{
int p = 7;
int q = 9;
swap(&p, &q);
cout << "p = " << p << "q= " << q << endl;
return 0;
}
Prints: p = 7q = 9
Inside your swap function, you are just changing the direction of pointers, i.e., change the objects the pointer points to (here, specifically it is the address of the objects p and q). the objects pointed by the pointer are not changed at all.
You can use std::swap directly. Or code your swap function like the following:
void swap(int *r, int *s)
{
int temp = *r;
*r = *s;
*s = temp;
return;
}
The accepted answer by taocp doesn't quite swap pointers either. The following is the correct way to swap pointers.
void swap(int **r, int **s)
{
int *pSwap = *r;
*r = *s;
*s = pSwap;
}
int main()
{
int *p = new int(7);
int *q = new int(9);
cout << "p = " << std::hex << p << std::endl;
cout << "q = " << std::hex << q << std::endl << std::endl;
swap(&p, &q);
cout << "p = " << std::hex << p << std::endl;
cout << "q = " << std::hex << q << std::endl << std::endl;
cout << "p = " << *p << " q= " << *q << endl;
return 0;
}
Output on my machine:
p = 0x2bf6440
q = 0x2bf6460
p = 0x2bf6460
q = 0x2bf6440
p = 9 q= 7
The line r=s is setting a copy of the pointer r to the copy of the pointer s.
Instead (if you do not want to use the std:swap) you need to do this
void swap(int *r, int *s)
{
int tmp = *r;
*r = *s;
*s = tmp;
}
You passed references to your values, which are not pointers. So, the compiler creates temporary (int*)'s and passes those to the function.
Think about what p and q are: they are variables, which means they are slots allocated somewhere in memory (on the stack, but that's not important here). In what sense can you talk about "swapping the pointers"? It's not like you can swap the addresses of the slots.
What you can do is swap the value of two containers that hold the actual addresses - and those are pointers.
If you want to swap pointers, you have to create pointer variables, and pass those to the function.
Like this:
int p = 7;
int q = 9;
int *pptr = &p;
int *qptr = &q;
swap(pptr, qptr);
cout << "p = " << *pptr << "q= " << *qptr << endl;
return 0;
You are not passing by reference in your example. This version passes by reference,
void swap2(int &r, int &s)
{
int pSwap = r;
r = s;
s = pSwap;
return;
}
int main()
{
int p = 7;
int q = 9;
swap2(p, q);
cout << "p = " << p << "q= " << q << endl;
return 0;
}
Passing by reference is not the same as passing by value or by pointer. See C++ tutorials on the web for an explanation. My brain is too small to waste cells storing the fine details I can find on the web easily.
If you are into the dark arts of C I suggest this macro:
#define PTR_SWAP(x, y) float* temp = x; x = y; y = temp;
So far this has worked for me.