从 argv[1] 在 C 中设置字符串变量 [英] Set string variable in C from argv[1]

查看:26
本文介绍了从 argv[1] 在 C 中设置字符串变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习 C,但我想知道为什么这不起作用?

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

推荐答案

你可以这样做:

char *testvar = argv[0];

或者:

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

正如 pmg 所指出的,strdup 不是标准的.使用 malloc + memcpy 实现它是一个很好的练习.

As pmg notes, strdup isn't standard. Implementing it using malloc + memcpy is a nice exercise.

甚至:

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

这篇关于从 argv[1] 在 C 中设置字符串变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆