Reputation: 2279
I'm having some trouble dealing with C-style strings in c++. In short what I'm trying to do is pass a cstring from my main method into the constructors of one of my objects.
For example
class sample
{
public: // Initalization
Sample( const char * inFile);
}//End sample class
Then in the main method.
//Main method
int main ( int argc, const char * argv[] )
{
Sample aSample(argv[1]);
}
Now, based on my assumption I should be getting back a const char*
when I dereference the second pointer using argv[1]
. From my understanding char *argv[]
is just another way of saying char **argv
.
Also, just to make sure my understanding of const is correct, const char *
is saying "this pointer points to a const char" where const char const *
is saying " this pointer address can not be changed, and the address it points to is const as well".
Update -
Just to clarify this is a two part question.
Updated my incorrect statement above that i dereferenced the "first" pointer when it should have been the "second". Thank you below for pointing that out.
2nd update - I'm using argv[1] because I'm receiving information from the command line and argv[0] holds only the path of the executable, which I'm not interested in.
Any help is greatly appreciated.
-Freddy
Upvotes: 0
Views: 2678
Reputation: 258568
argv[1]
dereferences the second pointer, not the first. You want argv[0]
. Arrays in C++ are 0-based.
Also:
const char const *
isn't legal (credits to Benjamin for pointing it out). Both const
s are applied to the char
in this case. If you want the pointer to be const, you need
char const * const
or
const char * const
EDIT:
Question 1) A CString can take a char*
as parameter for the constructor, so it should work.
Question 2) const
binds to the left, unless there's nothing to the left. So const char
and char const
are the same. For a const pointer, you need * const
, not const *
.
Upvotes: 3