I am trying to learn C, and I wonder why this doesn't work?
#include <stdio.h> int main(int argc, char *argv[]) { char testvar[] = argv[0]; //do something with testvar return 0; } 3 Answers
You could do this instead:
char *testvar = argv[0]; Or maybe:
char *testvar = strdup(argv[0]); /* Remember to free later. */ As pmg notes, strdup isn't standard. Implementing it using malloc + memcpy is a nice exercise.
Or even:
char testvar[LENGTH]; if (strlen(argv[0]) >= LENGTH) fprintf(stderr, "%s is too long!\n"); else strcpy(testvar, argv[0]); But then again you might be looking for:
char testvar[] = "testvar"; 0That syntax is valid only to initialize a char array from a literal, i.e. when you explicitly write in the source code what characters must be put in the array.
If you just want a pointer to it (i.e. "another name" to refer to it) you can do:
char * testvar = argv[0]; if instead you want a copy of it you have to do:
size_t len = strlen(argv[0]); char * testvar = malloc(len+1); if(testvar==NULL) { /* allocation failed */ } strcpy(testvar, argv[0]); /* ... */ free(testvar); You need a constant to initialize an object. argv[0] is not a constant.
"foobar" below is a constant
#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; }