[英]C: How do I pass a pointer of a string argument to a function?
The argv array is a list pointers, each pointing to the respective argument, with the first element the number of command line arguments, correct? argv数组是一个列表指针,每个都指向相应的参数,第一个元素是命令行参数的数量,对吗?
My question is how do I pass a string argument to a function? 我的问题是如何将字符串参数传递给函数? In this small example I'm just trying to print the text I write as argument in the command line.
在这个小例子中,我只是试图在命令行中打印我作为参数写的文本。
#include <stdio.h>
#include <stdlib.h>
void ptest(char *);
int main(int argc, char const *argv[])
{
ptest(argv[1]);
return 0;
}
void ptest(char *ptr)
{
printf("%s\n", ptr);
}
This code does not compile. 此代码无法编译。 It gives the following compilation errors:
它给出了以下编译错误:
teste2.c:8:8: warning: passing 'const char *' to parameter of type 'char *' discards qualifiers [-Wincompatible-pointer-types-discards-qualifiers]
ptest(argv[1]);
^~~~~~~
teste2.c:4:18: note: passing argument to parameter here
void ptest(char *);
^
That's not you issue. 那不是你的问题。 Your issue is that you've added the
const
keyword, meaning that you have a pointer to an array of values, where the array of values can't be changed. 您的问题是您添加了
const
关键字,这意味着您有一个指向值数组的指针,其中值的数组无法更改。
You can check out this for a better explanation. 您可以查看此信息以获得更好的解释。
In your code: 在你的代码中:
int main(int argc, char const *argv[])
remove the const
and your code will compile: 删除
const
,你的代码将编译:
int main(int argc, char *argv[])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.