C++ : cannot convert from 'char *' to 'char []' problem
im not a c/c+ pro开发者_如何学JAVAgrammer ( i do know delphi), anyway im trying to compile a program written in c++, i'v changed it to accept some arguments( a path to a file, which is hardcoded in the original code) from command line, the orignial line was
char Filepath[50] = "F:\\mylib\\*.mp3";
and i changed it to
char Filepath[50] = argv[1];
but i got "cannot convert from 'char *' to 'char []'" error, the main function is like
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
what should i do?? im using MSVC6.
thanks
Use:
char *Filepath = argv[1];
There's no need to allocate space for 50 characters when argv[1]
already contains the string you want. Also, you don't have to decide what will be the maximum number of characters in the command line argument; that space is already allocated for you.
Note, however, that the above will not make a copy of the string, so if you intend to modify the string (perhaps by appending an extension or anything), then you will have to use strcpy()
or similar solution. Handling strings in C is a lot more manual character-copying work than it is in Delphi.
char Filepath[50] = argv[1];
In order to copy a string as in the above example you need to use strcpy (or any of its variants)
Another (better) way is to use C++ strings
std::string Filepath = argv[1];
that would copy the string as well.
strncpy(Filepath, argv[1], sizeof Filepath - 1)
Or, "what Greg said".
Besides using strncpy() or std::string, it might be good to see why it goes wrong. I would recommend checking this faq to see the ins and outs of pointers and arrays. http://c-faq.com/aryptr/index.html
精彩评论