tags:

views:

394

answers:

4

hi, im not a c/c+ programmer ( 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

+5  A: 

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.

Greg Hewgill
thanks, i strcpy worked
avar
If strcpy() worked, and you copied a command line argument into a 50 byte buffer, you have a buffer overflow waiting to happen. Make sure you check the length of the string and fail if it too long, or use a function like strdup().
janm
+1  A: 

strncpy(Filepath, argv[1], sizeof Filepath - 1)

Or, "what Greg said".

DigitalRoss
Surely it's better to fail than silently truncate a pathname ... and in this case you need to remember termination if the string is too long ...
janm
If Filepath is global or static then it will always be null-terminated. I suppose it could be `auto`, then he should declare it as ` char Filepath[50] = { 0 };`, so the `strncpy()` call will always leave a null-terminated string. Anyway, it will fail soon enough, it's just a question of when.
DigitalRoss
Even if the string is null terminated (and we don't know how it was allocated), it will still be truncated and will still give the wrong result.
janm
+6  A: 
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.

Anders K.
or what Greg said :-)
Anders K.
This is better than what Greg said because it goes into std::string ...
janm
Why is that better, janm?For all we know the rest of the code uses char*.
Pod
Because there won't be overflow with a std::string, of course.
Matthieu M.
its 'better' in the sense that it works regardless of the string length of argv[1]
Anders K.
A: 

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

HeapOverflow