C:通过指针访问第二个 argv [英] C: Accessing the second argv via a pointer

查看:29
本文介绍了C:通过指针访问第二个 argv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我对 C 很陌生,所以我对指针还不太了解.我想检查命令行参数是否为整数,但在单独的函数中,以便传入 argv 数组的指针.

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;
}

我尝试了几件事情,主要是导致奇怪的 printf's(打印取消引用的指针以测试值时).

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.

推荐答案

argv 是一个二维数组,也就是说 argv 是一个数组的数组.具体来说, argv 是一个字符数组数组.现在,argv 存储的数据是从命令行传递给程序的参数,argv[0] 是程序的实际名称,其余的是参数.

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.

现在,要回答您的问题,您不需要将 argv 全部传递给函数check".您需要做的是传递 argvs 元素之一.这是因为检查"的参数是一个字符数组,而 argv 是一个字符数组的数组.所以尝试传递 argv[1] 来检查第一个参数.

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.

尝试检查除程序名称外的所有参数

#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;
}

这篇关于C:通过指针访问第二个 argv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆