C 参数字符数组
我想传递参数并将它们输出为字符或字符串数组。做到这一点最简单的方法是什么?一旦我将它们作为字符数组,我希望能够操作该数组。我能够传递它们并使用字符指针遍历字符串,但我想使用字符数组。有什么简单的方法可以做到这一点吗?我对 C 还很陌生,这是我到目前为止所掌握的。
if(argc != 3){
printf("incorrect number of arguments, program needs 3\n");
exit(1);
}
char s1[20];
s1 = (char*)argv[1];
char s2[20];
s2 = (char*)argv[2];
printf("String1 is %s\n", s1);
printf("String2 is %s\n", s2);
exit(0);
I would like to pass in arguments and output them as an array of characters or string. What is the easiest way to do this? Once I have them as an array of characters I want to be able to manipulate the array. I was able to pass them in and use a character pointer to traverse through the string but I'd like to use a char array. Is there any easy way to do this? Im pretty new to C, here is what I have so far.
if(argc != 3){
printf("incorrect number of arguments, program needs 3\n");
exit(1);
}
char s1[20];
s1 = (char*)argv[1];
char s2[20];
s2 = (char*)argv[2];
printf("String1 is %s\n", s1);
printf("String2 is %s\n", s2);
exit(0);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
argv 数组指向的字符串是可以修改的,你可以只修改argv 数组指向的字符串,不需要复制它们。
从C标准来看:
The strings pointed to by the
argv
array are modifiable, you can just modify the strings pointed to by theargv
array, there is no need to copy them.From the C standard:
您可以直接直接打印 argv 的值:
如果您需要修改字符串,请按以下方法操作
You can simply print the values of
argv
directly:If you need to modify the strings, here is how you would do that
argv[1]
和argv[2]
已经是指向字符数组的指针,因此您可以直接使用它们。此外(请参阅@ouah 的帖子),字符串已经是可变的,因此您可能根本不需要除此之外的任何内容。如果您确实想要一个作用域本地数组,则需要使用称为“可变长度数组”的 C99 功能,因为字符串长度仅在运行时已知:
或者您可以
malloc
足够的空间用于字符串的副本(例如 char * s1 = malloc(strlen(argv[1]) + 1);),但是这样你就没有本地毕竟数组(你可能会这样我们将使用原始字符串,除非您真的想复制)。argv[1]
andargv[2]
are already pointers to character arrays, so you can use those directly. Moreover (see @ouah's post), the strings are already mutable, so you might not need anything beyond this at all.If you really want to have a scope-local array, you need to use the C99 feature called "variable-length arrays", since the string lengths are only known at runtime:
Alternatively you could
malloc
enough space for a copy of the string (saychar * s1 = malloc(strlen(argv[1]) + 1);
), but then you wouldn't have a local array after all (and you might as well use the original strings, unless you really wanted to make a copy).argv
已经是char*
(实际上是数组的数组),但是,它们被标记为const
,如“不要修改”;) 。你想要的实际上是复制它们,这样你就可以自由地操纵它们:现在你可以按照你的意愿操纵 str 。
argv
is alreadychar*
(actually an array of an array), however, they are notedconst
as in "do not modify" ;). What you want is actually making a copy of them so you can manipulate them freely:Now you can manipulate str as you wish.