Home > Enterprise >  C char* as a function parameter
C char* as a function parameter

Time:02-22

How can I pass a char pointer (char*) to the function func()?

#include <iostream>
using namespace std;

void func(char *var)
{
    cout << var;
}

int main()
{
    char* test = "Hello World";
    func(test);
}

The compiler says:

Initialization: const char[12] cannot be converted to char *

CodePudding user response:

A string literal is a const char[N] array in read-only memory (where N is the number of characters in the literal, plus 1 for the null terminator, so in your case 11 1=12). You can't point a char* pointer (ie, a pointer to non-const data) at a string literal, as that would allow for the possibility of altering read-only data, which is undefined behavior.

Simply change your pointer type to const char* instead (ie a pointer to const data), eg.

#include <iostream>
using namespace std;

void func(const char *var)
{
    cout << var;
}

int main()
{
    const char* test = "Hello World";
    func(test);
}

Otherwise, as you say you have no control over the function declaration, then if you really want to pass a string literal to a char* pointer, you should copy the characters into a separate writable char[] buffer first, and then point at that instead, eg:

#include <iostream>
using namespace std;

void func(char *var)
{
    cout << var;
}

int main()
{
    char test[] = "Hello World";
    func(test);
}

Or, if you know for sure that the function will never modify the characters, you can just cast off the const-ness using const_cast (though this is highly NOT recommended, I'm including it for completeness), eg:

#include <iostream>
using namespace std;

void func(char *var)
{
    cout << var;
}

int main()
{
    char* test = const_cast<char*>("Hello World");
    func(test);

    /* alternatively:
    const char* test = "Hello World";
    func(const_cast<char*>(test));
    */
}

CodePudding user response:

This code would print the string "Hello World"

void func(char *var) 
{
    for( ;*var!='\0'; var  ) {  //!= from null terminator  
        cout<<*var;
    }
}
int main()
{
    char test[] = "Hello World";
    func(test);
    return 0;
}
  •  Tags:  
  • c
  • Related