如何将 argv 分配给 C 中的指针变量?
How to assign argv to a pointer variable in C?
我正在尝试打印传递给 C 程序的参数,我想打印多次。下面是代码。你可以看到,我创建了一个 count 变量并在每个 while 循环之前设置为 argc 。是否有与 argv 类似的东西,以便它可以在 while 循环之前重置为 argv[0]
?这是一个数组指针,我没有找到合适的方法。
#include <stdio.h>
int main(int argc, char const *argv[])
{
int count = argc;
while (count-- > 0)
{
printf("%s%s", *argv++, (count > 0) ? " " : "");
}
printf("\n");
count = argc;
while (count-- > 0)
{
// how to reset argv to point to argv[0] before calling *argv++
printf((count > 0) ? "%s " : "%s", *argv++);
}
printf("\n");
return 0;
}
你对argv
的定义是错误的。来自 C11 标准 §5.1.2.2.1/2::
The parameters argc and argv and the strings pointed to by the argv
array shall be modifiable by the program, and retain their last-stored
values between program startup and program termination.
应该是char **argv
或者char *argv[]
int main(int argc, char *argv[])
{
int count = argc;
char **savedArgv = argv;
while (count--)
{
printf("%s%s", *argv++, (count > 0) ? " " : "");
}
printf("\n");
count = argc;
argv = savedArgv;
while (count--)
{
// how to reset argv to point to argv[0] before calling *argv++
printf((count > 0) ? "%s " : "%s", *argv++);
}
printf("\n");
return 0;
}
我正在尝试打印传递给 C 程序的参数,我想打印多次。下面是代码。你可以看到,我创建了一个 count 变量并在每个 while 循环之前设置为 argc 。是否有与 argv 类似的东西,以便它可以在 while 循环之前重置为 argv[0]
?这是一个数组指针,我没有找到合适的方法。
#include <stdio.h>
int main(int argc, char const *argv[])
{
int count = argc;
while (count-- > 0)
{
printf("%s%s", *argv++, (count > 0) ? " " : "");
}
printf("\n");
count = argc;
while (count-- > 0)
{
// how to reset argv to point to argv[0] before calling *argv++
printf((count > 0) ? "%s " : "%s", *argv++);
}
printf("\n");
return 0;
}
你对argv
的定义是错误的。来自 C11 标准 §5.1.2.2.1/2::
The parameters argc and argv and the strings pointed to by the argv array shall be modifiable by the program, and retain their last-stored values between program startup and program termination.
应该是char **argv
或者char *argv[]
int main(int argc, char *argv[])
{
int count = argc;
char **savedArgv = argv;
while (count--)
{
printf("%s%s", *argv++, (count > 0) ? " " : "");
}
printf("\n");
count = argc;
argv = savedArgv;
while (count--)
{
// how to reset argv to point to argv[0] before calling *argv++
printf((count > 0) ? "%s " : "%s", *argv++);
}
printf("\n");
return 0;
}