int number = 5;
int* myPointer = &number; // Creates a pointer that points to the variable number
cout << *myPointer; // Dereferences the pointer to get the value and prints it
What exactly don't you understand about pointers? We need more details to be able to help you out. I assume this is for a assignment on pointers but generally when using C++ you will want to use smart pointers when possible.
We don't write code in pointer. We write code normally, as some kind of a function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
#include <string>
#include <cctype>
void say_hello( const std::string& name )
{
std::cout << "hello " << name << "!\n" ;
}
void print_uc( const std::string& name )
{
for( char c : name ) std::cout << char( std::toupper(c) ) ;
std::cout << '\n' ;
}
Once we have a function, we can create pointers that point to the function.
In much the same way as: once we have an int, we can create pointers that point to the int.
For instance:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int main()
{
const std::string n = "ishti alam" ;
auto ptr = &say_hello ; // ptr points to function 'say_hello'
ptr(n) ; // call the function that ptr points to
ptr = &print_uc ; // ptr now points to function 'print_uc'
ptr(n) ; // call the function that ptr points to
ptr = nullptr ;
// etc
}
I interpreted it to mean writing op codes into a buffer, using the OS' native API function to make the memory executable, and then executing the memory by casting it to a function and calling it. Isn't that writing code in pointer?
To make it even more complicated shouldn't you be using std::function to be passing around a function instead of a function pointer? I am still quite new to #include <functional> and functional programming in general so this is actually kind of a serious question. Is there benefits to using a function pointer over std::function? Or the other way around?
#include <iostream>
#include <string>
#include <functional>
usingnamespace std;
usingnamespace std::placeholders;
void say_hello( const std::string& name )
{
std::cout << "hello " << name << "!\n" ;
}
void print_uc( const std::string& name )
{
for( char c : name ) std::cout << char( std::toupper(c) ) ;
std::cout << '\n' ;
}
class MyStuff
{
public:
void printGoodbye(const std::string& name)
{
std::cout << "Goodbye " << name << "!\n";
}
};
int main()
{
const std::string n = "ishti alam";
MyStuff goodClass;
// Create the function object to hold the function
std::function<void(const std::string&)> stuff = say_hello;
// Call that function object
stuff(n);
// Well I am bored with that funtion time for a new one.
stuff = print_uc;
// Call the new one.
stuff(n);
// Now we work with methods!
stuff = std::bind(&MyStuff::printGoodbye, &goodClass, _1);
stuff(n);
}
Sorry to the OP ;p Though if you do still need help just let us know with a more detailed post what you are having trouble with exactly.