简体   繁体   中英

Passing pointer to function and getting its value inside that function

Pseudocode below shows what I am trying to achieve. I am new to C++ and pointers, as you can guess from this question. So, I don't know what to pass to function [1], what to get from parameter [2], and what to use to make comparison [3].

Please do not ask why I am passing a pointer instead of the value itself, the function only accepts pointers for this task.

I need some help.

main {
   string someString = ..
   function(pointer of the string above [1]*);
}

function (parameter[2]*) {
   if (parameter[3]* == "Hello World") {
      print("okay");
   }
}

It depends on what language you are using.

In C++ the program can look like

#include <iostream>
#include <string>

void check( const std::string &s )
{
    if ( s == "Hello World" ) 
    {
        std::cout << "okay" << '\n';;
    }
}

int main() 
{
   std::string someString = "Hello World";

    check( someString );
}

In C a corresponding program can look like

#include <stdio.h>
#include <string.h>

void check( const char *s )
{
    if ( strcmp( s, "Hello World" ) == 0 ) 
    {
        puts( "okay" );
    }
}

int main( void ) 
{
   char someString[] = "Hello World";

    check( someString );
}

A similar program using a character array is also can be written in C++.

Instead of the declaration of the array

   char someString[] = "Hello World";

you could declare a pointer to the string literal like

   const char *someString = "Hello World";

You have a couple of options here:

  • Pass the string variable by reference
  • Make the variable a pointer itself

By passing the variable by reference, you will change the main string, unless your function accepts the pointer as constant. You can do that by doing the following:

main {
   string someString = ...;

   // Notice here we are passing the variable by reference
   // We are passing the variable's address to the function
   function(&somestring);
}

And with the second option, you can do the following:

main {
   string* someString = new string(...);

   // Pass it normally, as it will be accepted
   function(someString);
}

And in the function itself you can use that value as it follows:

function(paramString) {
   if(*paramString == "Hello World") {
       do something..
   }
}

Please read some more information about function parameters and arguments, and about pointers itself.

The links below will give you a head start.

https://www.w3schools.com/cpp/cpp_function_param.asp https://www.w3schools.com/cpp/cpp_pointers.asp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM