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

查看:98
本文介绍了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(在打印取消引用的指针以测试值时).

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是char数组的数组.现在,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元素之一.这是因为要检查"的参数是一个char数组,而argv是一个char数组.因此,请尝试传递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天全站免登陆