Set string variable to C from argv [1]

I am trying to learn C and I wonder why this is not working?

#include <stdio.h>

int main(int argc, char *argv[])
{
    char testvar[] = argv[0];
    //do something with testvar

    return 0;
}
+5
source share
3 answers

Instead, you can do this:

char *testvar = argv[0];

Or maybe:

char *testvar = strdup(argv[0]);
/* Remember to free later. */

As pmg notes , strdupit is not standard. Implementing it with malloc + memcpy is a great exercise.

Or even:

char testvar[LENGTH];
if (strlen(argv[0]) >= LENGTH)
    fprintf(stderr, "%s is too long!\n");
else
    strcpy(testvar, argv[0]);

But again, you can search:

char testvar[] = "testvar";
+6
source

This syntax is only valid for initializing an array charfrom a literal, i.e. when you explicitly write to the source code which characters should be placed in the array.

If you just need a pointer to it (that is, a “different name” to refer to it), you can do:

char * testvar = argv[0];

if you want to get a copy of it:

size_t len = strlen(argv[0]);
char * testvar = malloc(len+1);
if(testvar==NULL)
{
    /* allocation failed */
}
strcpy(testvar, argv[0]);
/* ... */
free(testvar);
+1

. argv[0] . "foobar" -

#include <stdlib.h>
#include <string.h>

int main(int argc char **argv) {
    char array[] = "foobar"; /* array has 7 elements */
    char *testvar;

    testvar = malloc(strlen(argv[0]) + 1); /* remember space for the NUL terminator */
    if (testvar != NULL) {
        strcpy(testvar, argv[0]);
        /* do something with testvar */
        free(testvar);
    } else {
        /* report allocation error */
    }
    return 0;
}
+1

All Articles