Search code examples
carraysstringcommand-line-argumentscopying

How to memcpy() from argv[]?


I want to copy string from argv[0] but I don't know how to get the size of argv[0].

How to do this?

int main(int argc, char* argv[])
{
  char str[20];
  if(argc>0)
      memcpy(str, argv[0], sizeof(argv[0]));
}

Solution

  • Since argv[0] is a string, use strlen.

    #include <string.h>
    
    size_t length = strlen (argv[0]) + 1;
    
    memcpy (str, argv[0], length);
    

    By the way, you could also use strcpy, which is more suitable for strings.

    #include <string.h>
    
    strcpy (str, argv[0]);
    

    In every case, in order to make sure that your copy won't overflow, you should check whether the size of str is sufficient.

    if (sizeof str >= length)
    {
      /* Do the copy. */
    }
    else
    {
      /* Report an error, or use dynamic allocation. */
    }