Reputation: 489
void Display(char* word)
{
static char* pointerToWord = word;
cout << pointerToWord;
}
void initialise(char* word)
{
Display(word);
}
void main()
{
char* word[3];
char* currentWord;
word[0] = "Hello";
word[1] = "World";
word[2] = "hahahaha";
currentWord = word[0];
initialise(currentWord);
currentWord = word[1];
//Displays word[0]
Display(0);
currentWord = word[2];
//Still Displays word[0]
Display(0);
}
Char* were always a bit of a pain in the neck. Can you help me get syntax right?
All I want is
initialise()
Display()
's pointer to a current word
use Display()
to display wherever the pointer is pointing to
In reality I've got a few classes involved, but this example pretty much illustrates the problem. Also I have no intention of modifying the string, so the strings are constant.
Upvotes: 0
Views: 181
Reputation: 310910
I think you mean something like the following
void Display( const char* word = nullptr )
{
static const char* pointerToWord;
if ( word != nullptr ) pointerToWord = word;
if ( pointerToWord != nullptr ) std::cout << pointerToWord;
}
Take into account that the function behaviour will be undefined if the object pointed to by pointerToWord is not alive.
Otherwise you should store a copy of the object in the function.
For example
#include <iostream>
#include <memory>
#include <cstring>
void Display( const char *word = nullptr )
{
static std::unique_ptr<char[]> pointerToWord;
if ( word != nullptr )
{
pointerToWord.reset( std::strcpy( new char[std::strlen( word ) + 1], word ) );
}
if ( pointerToWord != nullptr ) std::cout << pointerToWord.get() << std::endl;
}
int main()
{
const char *word[2] = { "Hello", "World" };
Display( word[0] );
Display();
Display( word[1] );
Display();
return 0;
}
The program output is
Hello
Hello
World
World
Take into account that function main in C++ shall have return type int
and string literals have types of constant character arrays.
Upvotes: 1
Reputation: 1775
Change the code as follows: first put pointerToWord
at global scope:
static char* pointerToWord = "";
overload Display function:
void Display()
{
cout << pointerToWord;
}
void Display(char* word)
{
pointerToWord = word;
Display();
}
Upvotes: 1