Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I handle argv character array assignments?

Tags:

c

argv

I found two ways of passing command-line arguments into a character array:

int main (int argc, char **argv)
{
  const char *s1 = argv[0];
  char s2[256];
  strcpy(s2, argv[0]);

  printf("s1: %s\ns2: %s\n\n", s1, s2);
}

Compiled with the IBM xlc compiler on an AIX system Returns

[MyPrompt]> ./a.out

s1: ./a.out

s2: ./a.out

Which implementation (s1 or s2) is correct? s1 is nice because argv[0] can be any length. s2 requires that the length of argv[0] < 256 characters.

I do not understand how/why s1 should work. I think the right-hand side of s1 should be required at compile time, but I think it's generated at run-time.

like image 493
Pete Avatar asked Dec 29 '25 22:12

Pete


2 Answers

The reason s1 works is because the type of argv[0] is a pointer. You are simply assigning the address (not the actual value), which is safe. You aren't performing any kind of allocation or cast.

I typically prefer the first option as you should only be reading from the argument variables.

like image 164
Jordan Parmer Avatar answered Dec 31 '25 12:12

Jordan Parmer


If you don't want to change the string then s1 will work.

If you want change the string then you can make a copy of it. You should use the safer strnlen() and strncpy() though if your system supports it.

like image 39
Karl Voigtland Avatar answered Dec 31 '25 13:12

Karl Voigtland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!