The argv array is a list pointers, each pointing to the respective argument, with the first element the number of command line arguments, correct?
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.
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:
int main(int argc, char *argv[])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.