P.C. Blazkowicz
P.C. Blazkowicz

Reputation: 489

Passing address of a char* C++

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

Upvotes: 0

Views: 181

Answers (2)

Vlad from Moscow
Vlad from Moscow

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

GreatAndPowerfulOz
GreatAndPowerfulOz

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

Related Questions