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.
- If the constructor in sample is incorrect for passing a cstring, how can I correct it?
- Understanding of const
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
argv[1]dereferences the second pointer, not the first. You wantargv[0]. Arrays in C++ are 0-based.Also:
isn’t legal (credits to Benjamin for pointing it out). Both
consts are applied to thecharin this case. If you want the pointer to be const, you needor
EDIT:
Question 1) A CString can take a
char*as parameter for the constructor, so it should work.Question 2)
constbinds to the left, unless there’s nothing to the left. Soconst charandchar constare the same. For a const pointer, you need* const, notconst *.