I
I
Issue2021-11-02 22:24:30
linux
Issue, 2021-11-02 22:24:30

How to pass functions("string") in C++?

Trying to pass a "string array" to the function but it throws an error along with the correct output.

C++:

#include <iostream>
#include <cstring>
using namespace std;

void echo(char* string){
  cout << string << endl;
}

int main(){
  echo("abc");
  return 0;
}


Terminal:
linux>~>cpp> ./build.sh 
main.cpp: In function ‘int main()’:
main.cpp:10:7: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
   10 |  echo("abc");
      |       ^~~~~
abc

Answer the question

In order to leave comments, you need to log in

3 answer(s)
U
User700, 2021-11-02
@paulenot

You need const char*
And yes, the name coincided with the standard class - not good

V
vanyamba-electronics, 2021-11-02
@vanyamba-electronics

string is the name of the STL class.

void echo(char* str){
  cout << str << endl;
}

P
Peter, 2021-11-02
@Morpheus_God

It is possible through the index

void printer(char *str)
{
    cout << str << endl;
  
}

It is possible through a char array
void printer(char str[])
{
    cout << str << endl;
  
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question