问题
As I'm quite new to C, there's something I don't yet get about pointers. I'd like to check wether a command line argument is integer or not, but in a separate function, so that I pass in the pointer of the argv array.
int main(int argc, char* argv[]){
if(check(argv)){
// Do stuff to argv[1]
}
}
int check(char* p){
// Test wether p+1 is int
return 1;
}
I have tried several things mostly resulting in weird printf's (when printing the dereferenced pointer to test the value).
int i = atoi(argv[1]);
Works just fine, of course. But as the pointer is the only thing passed to the function, I'm paralysed.
回答1:
Argv is a two dimensional array, which is to say that argv is an array of arrays. Specifically, argv is an array of char arrays. Now, the data that argv is storing is the arguments passed from the command line to the program, with argv[0] being the actual name of the program and the rest being the arguments.
Now, to answer your question, you need to not pass argv in its entirety to the function "check". What you need to do is pass one of argvs elements. This is because the parameter to "check" is a char array, and argv is an array of char arrays. So try passing argv[1] to check the first argument.
Edit: Try this to check all arguments except the name of the program
#include <stdio.h>
#include <ctype.h>
int main(int argc, char* argv[]) {
for (int i = 1; i < argc; ++i) {
if( check(argv[i]) ){
// Do stuff to argv[i]
}
}
int check(char* p){
int i = 0;
char c = p[i];
while (c != '\0') {
if (!isdigit(c))
return 0;
c = p[++i];
}
return 1;
}
回答2:
int check(char* p){
The above function expects a pointer to a char
while you are passing argv
which is array of char *
Try
int check(char* p[]){
Also before using argv[1]
check if argv[1]
exists ie check argc
int main(int argc, char* argv[]){
if(argc>1 && check(argv)){
// Do stuff to argv[1]
}}
回答3:
Before indexing an array of pointer, we have to be sure it's valid. We have to use argc
to this purpose.
strtol is a function which parse a string and detect error if it's not of the base asked.
Ty this:
int main(int argc, char* argv[]){
if(check(argc, argv)){
// Do stuff to argv[1]
}
}
int check( int argc, char * argv[] ){
if( argc > 1 ) {
char * err = NULL;
strtol( argv[1], &err, 10 );
return argv[1][0] != '\0' && *err != '\0';
}
return 0;
}
来源:https://stackoverflow.com/questions/42143007/c-accessing-the-second-argv-via-a-pointer