Set string variable in C from argv[1]

六月ゝ 毕业季﹏ 提交于 2021-02-16 04:49:33

问题


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;
}

回答1:


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";



回答2:


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);



回答3:


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;
}


来源:https://stackoverflow.com/questions/9017220/set-string-variable-in-c-from-argv1

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!