Converting Char * to Const Char[]

Hi,

I am new to C++ coding. I am trying to convert Char * to Const Char[] but I am not able to do it.

Here is the snippet

bool Method (Char *location)
{
static const char FileName[]= strcat(location, "\\Root");
}

I am getting this error:

error C2440: 'initializing' : cannot convert from 'char *' to 'const char []'

Can someone please explain and correct me.

Thanks in advance
That's not how strcat works, which you don't use in C++ anyway. The correct version looks like this:

1
2
3
4
5
bool method(std::string location)
{
    const std::string fileName=location+"\\Root";
    [...]
}


Are you sure you know what static does?
Last edited on
That isn't the way to initialize an array. The only exception is if you're using a string literal, which you're not.

If you try compiling:

1
2
3
4
5
6
7
#include <cstring>

bool Method (char *location)
{
    static const char FileName[]= { std::strcat(location, "\\Root") };
    return true ;
}


I get:
Error	1	error C2440: 'initializing' : cannot convert from 'char *' to 'const char'


which I expected. You can't initialize a char with a pointer.

1
2
3
4
5
6
7
#include <string>

bool Method (std::string location)
{
    static const std::string FileName = location + "\\Root" ;
    return true ;
}


works just fine, however.

Caution: using static data in Method means that the argument you supply to Method in subsequent calls will not be used to initialize FileName.
Thanks for your replies cire and Athar.

I tried the way suggested by Cire and it worked but the problem is after I get the FileName I need to pass it to a Method whose input argument is a Char *. Since the FileName will be of type std::string it is giving me an error

error C2664: : cannot convert parameter 1 from 'const std::string' to 'const char *'







Use method of class std::string c_str()

For example

std::string s( "Tets" );

std::cout << s.c_str() << std::endl;
Thanks Vlad, I used c_str() to convert std::string to char * and was able to achieve what I wanted to do.


Thank you guys (cire and Athar)
You may not use c_str() as an argument for a parameter of type char *. The parameter shall be declared as const char *
Last edited on
Topic archived. No new replies allowed.