简体   繁体   中英

C++ Passing C-style string as argument

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.

  1. If the constructor in sample is incorrect for passing a cstring, how can I correct it?
  2. 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 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 * .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM