tags:

views:

74

answers:

3

Hi,

I am writing a C program. It takes its arguments from commandLine. I want to change the commandLine arguments in the code. As they are defined as "const char *", I can not change them using "strcpy", "memcpy", ... Also, you know, I can not just change their type from "const char *" to "char *". Is there any way to change them?

Thank you so much in advance.

Best regards, Shadi.

+1  A: 

No, you are not allowed to modify those. However, there's no rule against copying them to a new buffer and using those instead.

rlbond
+7  A: 

According to C99 §5.1.2.2.1/1, the signature for main is

int main(int argc, char *argv[]) { /* ... */ }

So you are allowed to remove the const. Just don't cause a buffer overrun by strcpying in longer strings than the original arguments, or attempting to install more arguments than originally passed.

Everyone else is basically right that you should create a copy instead.

Potatoswatter
One of those awesome vectors of strings that C doesn't have? ;-)
James McNellis
@James: rofl, serves me right for processing too many questions at a time.
Potatoswatter
And even more than just what you might infer from the parameter types, the standard specifically says: "The parameters argc and argv and the strings pointed to by the argv array shall be modifiable by the program..."
Michael Burr
+1  A: 

This may be beside the point, but you can't change anything with neither strcpy() nor memcpy(); the suffix 'cpy' is short for copy (unsurprisingly.)

Regarding changing the argv pointer, you could of course change the pointer, but why? If you want the command line arguments to be something other than what's given, just ignore them, and use whatever values you prefer. Also note that argv is a parameter and thus local to main(); if it is needed elsewhere, you have to either pass it as a parameter, or save it as a global variable.

olaan
re. “you can't change anything with `strcpy()`”; if it didn't change anything, it would be quite pointless. If you do `strcpy(argv[0], "foo");`, it changes (the contents of) `argv[0]`.
Arkku