Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set string variable in C from argv[1]

Tags:

c

variables

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;
}
like image 919
systemio Avatar asked Jan 26 '12 11:01

systemio


2 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";
like image 110
cnicutar Avatar answered Oct 17 '22 08:10

cnicutar


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);
like image 25
Matteo Italia Avatar answered Oct 17 '22 07:10

Matteo Italia