无法弄清楚如何正确存储命令行参数

Can't figure out how to store command line arguments correctly

我需要存储两个命令行参数,但我不知道如何正确地这样做。我的代码当前存储了一个不正确的 int(如果我将第二个变量设置为空)并给出了一个错误,指出初始化无效。我尝试使用 strcpy 和 strcat 初始化名称,但这也无济于事,因为我遇到了主要与转换有关的不同错误。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

int main(int argcount, char *args[])
{
   int number = *args[1];
   char name[] = *args[2];


   printf("number is %d and name is %s\n", number, name);

   return 0;
}

您的主要功能应该如下所示:

int main(int argcount, char **args)
{
   int number = atoi(args[1]); // atoi() converts your string to an int
   char *name = args[2]; // Do not dereference twice, otherwise you get a char


   printf("number is %d and name is %s\n", number, name);

   return 0;
}

int number = *args[1]; 是错误的,因为 args[1] 是您的第一个参数,而 *argv[1](或 argv[1][0])是您参数的第一个字母。将其放入 number 变量中实际上会导致第一个参数的第一个字母的 ASCII 值存储在 number 中。这绝对不是你想要的。

char name[] = *args[2]; 也不正确,因为在这里,您试图获取第二个参数(*args[2]args[2][0])的第一个字母,这是一个类型 char 并将其放入 char.

数组中

您可能还想检查您的程序获得了多少参数以及这些参数的格式是否正确,否则您的程序可能会崩溃!

请注意所有cmdline args都是在字符串中给出的(一系列字符,所以如果你想使用它们作为它们的字面意思,你必须转换它们:

#include <stdlib.h>

int number = atoi(args[1]);
char *name = args[2];

如果你想复制args[2],你应该使用strcpy:

#include <string.h>

char name[1+strlen(args[2])];
strcpy(name, args[2]);

// Now this works:
printf("number is %d and name is %s\n", number, name);

最后,建议您检查是否给定了足够的参数,这样您就不会越界访问args