Why is the value of a pointer to a function 1 [duplicate] - c++

This question already has answers here:
How to print function pointers with cout?
(7 answers)
Closed 6 years ago.
I understand functions like data items have addresses and the address of a function is the memory address where the stored machine language code for the function begins. I have this code;
#include <iostream>
using namespace std;
int x(int);
char * y(char *);
int main() {
x(5);
y("hello");
int (*p) (int); //pointer to function x
char * (*q) (char *); //pointer to function y
p = &x; //holds the address of function x
q = &y; //holds the address of function y
cout << p << endl;
cout << q;
return 0;
}
int x(int a) {
return (a * a);
}
char * y(char *b) {
return (b);
}
So is there a way i can force the cpu to execute a particular function before another using the function addresses?
Upon compiling, the program prints out both addresses as 1. I was expecting hexadecimal values like that of data items. even when I print the dereferenced values, I still get 1, what is going on?
Also, if both function addresses are 1, how does the cpu know which function to execute first?
EDIT:
one of my questions is left unanswered, which i find very important! Doesn't wholly make it a duplicate even though some are.

The std::cout will convert function pointers to a bool, and since the function pointer is non-zero, the value 1 is displayed.
To display as hex value, cast the function pointer to a void *, for example:
cout << (void*)p << endl;

You can retrieve these functions addresses by typing :
cout<< &p << endl << &q << endl;
The & operator gives you back the address of block memory in which the variable after the & operator is set.

Related

Different value of &array in main() and in function() [duplicate]

This question already has answers here:
Passing Arrays to Function in C++
(5 answers)
What is array to pointer decay?
(11 answers)
Closed 4 months ago.
I'm sorry for my bad English first.
I've encountered a strange problem when coding in C++.
using namespace std;
void Func(int a[2][3])
{
cout <<(int) &a;
}
int main()
{
int a[2][3] =
{
{1,2,3},
{4,5,6}
};
cout << (int)&a << endl;
Func(a);
return 0;
}
I was confused that &a in main() and in function Func() returned different values. And strangely, the difference between them always is 212.
Can anyone explain please? Thank you for your help.
P/s:Thank you all for your answer .My teacher says that C++ doesn't allow passing an array by value, because if the array has 1 million elements, that would decrease the performance a lot only for copying all of them, so he says only pass by reference is allowed. That's what make me think those two &a should be the same. Now I get it, thank you everyone!
Your function declaration
void Func(int a[2][3])
is completely equivalent and interchangeable with:
void Func(int (*a)[3]).
As you can see, you are passing a pointer to an array of three ints by value. Therefore the address of the local function parameter is different from the address of the variable in main, even if they may hold the same value.
You're passing the a argument by value, so each function has its own copy of it (of the pointer, not the array data). The constant offset you're seeing comes from the distance between the stack frames of the two functions, and this is constant.
If you change the function to get a reference to the array (void Func(int (&a)[2][3]) you will get the same value in both cases
The parameter and the local variable are distinct objects and since their lifetimes overlap, they must have distinct memory addresses.
Please read about pass by value and pass by references.
So what happened here is:
you initialised an array in main function. &a will refer to the address of a.
you passed as a pass by value argument to another function. A copy of a is created to be consumed in Func and &a will refer to the memory location of a local to Func.
I hope the concept is clear.
Use the following syntax to pass arrays by (const) reference : const int (&a)[2][3]
#include <iostream>
void func(const int (&a)[2][3])
{
for (const auto& row : a)
{
for(const auto& value : row )
{
std::cout << value << " ";
}
std::cout << "\n";
}
}
int main()
{
int a[2][3] =
{
{1,2,3},
{4,5,6}
};
func(a);
return 0;
}
This is because C rules on how pointers and arrays work are a little weird. You're actually taking the address of a pointer to the array, not the actual address of the array. If you want to get the address to the array you need to take the address of the first element instead:
&a[0]
For starters it is a bad idea to cast an address to the type int like
cout << (int)&a << endl;
you could just write
cout << static_cast<void *>( a ) << endl;
or
cout << static_cast<void *>( &a ) << endl;
Or even like
cout << a << endl;
cout << &a << endl;
though with static_cast the code looks more readable.
The both statements will output the same value: the address of the extent of memory occupied by the array.
In this function call
Func(a);
the array designator is implicitly converted to pointer to its first element of the type int( * )[3].
The value of the pointer expression is assigned to the local variable (parameter) a of the function Func.
The function parameter of the pointer type a and the array a defined in main occupy different extents of memory.
If to rename the function parameter as for example
void Func(int b[2][3])
to distinguish it from the array with the same name defined in main then you may imagine the function call the following way
Func(a);
//...
void Func( /*int b[2][3] */ )
{
int ( *b )[3] = a;
cout << static_cast<void *>( &b );
}
Pay attention to that the function parameter declared as having the array type int[2][3] is implicitly adjusted by the compiler to pointer to the array element type that is int ( * )[3].
So as you can see this statement
cout << static_cast<void *>( &b );
outputs the address of the local variable (parameter) b.
If you want to get the address of the array a within the function Func then you should write
cout << static_cast<void *>( b );
In this case the addresses outputted in main and in the function will coincide because the parameter b stores the address of the first element of the array a.
Here is a demonstration program.
#include <iostream>
void Func( int a[2][3] )
{
std::cout << static_cast< void * >( a ) << '\n';
}
int main()
{
int a[2][3] =
{
{1,2,3},
{4,5,6}
};
std::cout << static_cast<void *>( a ) << '\n';
std::cout << static_cast<void *>( &a ) << '\n';
Func( a );
}
The program output might look like
010FFD08
010FFD08
010FFD08
As you can see the three values are equal each other.
But if you will write in the function Func
std::cout << static_cast< void * >( &a ) << '\n';
^^^^
you will get the address of the local variable (parameter) a of the function. It is evident that this address differs from the address of the extent of memory occupied by the array because for the parameter a there was allocated a separate extent of memory the size of which is equal tp the value of the sizeof( int( * )[3] ) and usually this value is equal to 4 or 8.

Is it OK to pass reference to a pointer as a function argument? [duplicate]

This question already has answers here:
Does int * & has any real sense?
(6 answers)
Closed 1 year ago.
I had the understanding that in c++ & and * cancel each other i.e int *&p is essentially equal to p as its value at address of integer p.
Now is it valid to pass reference to a pointer in view of above i.e say i am trying to pass reference to a pointer as an argument in a function as below?
void func(int* &p)
Won't the above result in cancellation of * with & and will just be int p?
How correct is it if i try to pass reference to pointer of a class object on similar terms?
#include <iostream>
using namespace std;
int gobal_var = 42;
// function to change Reference to pointer value
void changeReferenceValue(int*& pp)
{
pp = &gobal_var;
}
int main()
{
int var = 23;
int* ptr_to_var = &var;
cout << "Passing a Reference to a pointer to function" << endl;
cout << "Before :" << *ptr_to_var << endl; // display 23
changeReferenceValue(ptr_to_var);
cout << "After :" << *ptr_to_var << endl; // display 42
return 0;
}
You are correct that the & address-of operator and the * indirection operator cancel each other out when used inside an expression.
However, when used inside a declaration, these operators have a very different meaning. Inside a declaration, * means "pointer" and & means "reference". Therefore, when used inside a declaration, they do not cancel each other out.
An object of type int*& is simply a reference to a pointer to an int.

What is (int*)?

I was trying to access the private data members of the class. Everything was going fine until I came upon the int*. I don’t get what it is. I think it’s something that we can use to create a new memory address.
My code :
#include <iostream>
using namespace std;
class x
{
int a, b, c, d;
public:
x()
{
a = 100;
b = 200;
c = 300;
d = 400;
}
};
int main()
{
x ob;
int *y = (int *)&ob;
cout << *y << " " << y[1] << " " << y[2] << " " << y[3] << endl;
}
Can anyone help me in understanding it?
Its a c-style cast to access the memory occupied by the struct x as a set of ints.
It takes the address of ob, casts it from 'address of' (ie a pointer to) x into a pointer to int. The compiler happily assigns this cast to y, so you can manipulate it, or in this case, print out the memory blocks as ints. As the struct happens to be a group of ints anyway, it all works even though its a bit of a hack. I guess the original coder wanted to print out all 4 ints without having to specify each one in turn by variable name. Lazy.
Try using a cast to a char* (ie 1 byte at a time) and print those out. You'll be basically printing out the raw memory occupied by the struct.
A good C++ way would be to create an operator<< function that returns each variable formatted for output like this, then write cout << ob << endl; instead.

Pointer in function parameters c++ [duplicate]

This question already has answers here:
C++ * vs [] as a function parameter
(3 answers)
Closed 9 years ago.
Consider this piece of code:
char strName[25];
void SetInfo(char *strName)
{
strncpy(m_strName, strName, 25);
}
Why are they using a pointer in the function parameter? Can't we just do this:
void SetInfo(char strName[]) {
strncpy(m_strName, strName, 25); }
? What is the difference between both?
Thank you
In this particular case, none at all (aside from one more letter to type). A char array "decays" to a pointer when passed to a function.
arrays always decay as pointers when passing as parameters.
in this case array is like a pointer (they point to the memory of the first element of the array)
void foo(char a[])
{
a[0] = '#';
cout << a[0];
cout << *a;
}
Both calls to cout prints the same character '#'.
void foo(char a[])
{
// gives you the size of a pointer to the array's data type.
// prints 4
sizeof(a);
// prints char *
cout << typeid(a).name();
}
I'm not sure if this is standard.

C++ pointer question

still working at C++, but this came up in my book and I don't understand what it's for:
MyClass * FunctionTwo (MyClass *testClass) {
return 0;
}
My question is what is the signifigance of the first indirection operator
(MyClass *[<- this one] FunctionTwo(MyClass *testClass))?
I tried making a function like it in codeblocks, with and without the first * and I didn't see any difference in the way it ran or it's output:
int *testFunc(int *in) {
cout << in << endl;
cout << *in << endl;
return 0;
}
int testFuncTwo(int *in) {
cout << in << endl;
cout << *in << endl;
return 0;
}
I couldn't find anywhere that explained about it in my book.
Thanks,
Karl
The MyClass * means that this function returns a pointer to a MyClass instance.
Since the code is actually returning 0 (or NULL) this means that any caller to this function gets back a NULL pointer to a MyClass object.
I think the following are better examples:
int *testFunc(int *in) {
cout << "This is the pointer to in " << in << endl;
cout << "This is the value of in " << *in << endl;
return in;
}
int testFuncTwo(int *in) {
cout << "This is the pointer to in " << in << endl;
cout << "This is the value of in " << *in << endl;
return *in;
}
void test() {
int a = 1;
cout << "a = " << a;
int output = *testFunc(&a); // pass in the address of a
cout << "testFunc(a) returned " << output;
output = testFuncTwo(&a); // pass in the address of a
cout << "testFuncTwo(a) returned " << output;
}
Apologies, but I've not done C++ in years but the syntax may be a little off.
The general format for a function that takes a single value and returns a single value in C++ is:
return_type function name ( parameter_type parameter_name )
In your case, return_type is MyClass *, which means "pointer to MyClass"
In addition, in your case, parameter_type is also MyClass *.
In other words, your code could be rewritten as:
typedef MyClass *PointerToMyClass;
PointerToMyClass FunctionTwo (PointerToMyClass testClass)
{
return 0;
}
Does that look more familiar?
Given the nature of the question, I'm going to provide a somewhat crude answer.
A pointer points to something:
int x = 123; // x is a memory location (lvalue)
int* y = &x; // y points to x
int** z = &y; // z points to y
In the above code, z points to y which points to x which stores an integral, 123.
x->y->z[123] (this is not code, it's a
text diagram)
We can make y point to another integer if we want or NULL to make it point to nothing, and we can make z point to another pointer to an integer if we want or NULL to make it point to nothing.
So why do we need pointers which point to other things? Here's an example: let's say you have a simple game engine and you want to store a list of players in the game. Perhaps at some point in the game, a player can die by having a kill function called on that player:
void kill(Player* p);
We want to pass a pointer to the player, because we want to kill the original player. Had we done this instead:
void kill(Player p);
We would not kill the original player, but a copy of him. That wouldn't do anything to the original player.
Pointers can be assigned/initialized with a NULL value (either NULL or 0) which means that the pointer will not point to anything (or cease to point to anything if it was pointing to something before).
Later you will learn about references which are similar to pointers except a pointer can change what it points to during its lifetime. A reference cannot, and avoids the need to explicitly dereference the pointer to access the pointee (what it's pointing to).
Note: I kind of skirted around your original question, but the sample code you provided has no inherent meaningful behavior. To try to understand that example without first understanding pointers in a general sense is working backwards IMHO, and you'd be better to learn this general theory first.
If you had something like int * Function() this would return a pointer to an integer. MyClass * just means that the function is going to return a pointer to an object of type MyClass. In c++ user defined objects are treated as first-class-objects, so once you create your own objects they can be passed as a parameter, returned from a subroutine, or assigned into a variable just like the standard types.
In the code blocks you posted there will be no difference in the output to the console because the thing you have changed is the type that the function returns (which is not used), the contents of the functions are identical.
When you define:
int *testFunc(int *in)
You are defining a function which returns a pointer to an int variable.
int testFuncTwo(int *in)
Returns just an int variable.
Zero in this case is undergoing an implicit cast - the first function returns (int*) 0, the second just 0. You can see this implicit cast in action if you change the prototype of your example function from returning a MyClass* to just returning a MyClass - if there's no operator int method in MyClass, you'll get a nice error.