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;
}
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";
That 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With