我该如何正确地传递这个数组c字符串? [英] How do I pass this array of c strings correctly?

查看:107
本文介绍了我该如何正确地传递这个数组c字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的C-字符串数组声明为:

I have my array of C-Strings declared as:

char *argv[MAXARGS];

MAXARGS基本上只是告诉我们有多少C字符串是数组索引的目的英寸
我想将它传递给下面这个函数...

MAXARGS basically just tells us how many c strings are in the array for indexing purposes. I want to pass it to this function below...

int builtin_cmd(char **argv)

但似乎没有穿过去,我调用该函数是这样的。

but nothing seems to go through, I called the function like this.

    char *argv[MAXARGS];

    builtin_cmd(argv);

但一旦我进入功能 builtin_cmd 并尝试使用打印

printf("%s\n", argv[0]);

它打印什么....但是当我在调用之前做到这一点...

it prints nothing.... but when i do this before calling the function...

char *argv[MAXARGS];
printf("%s\n", argv[0]);
//builtin_cmd(argv);

将打印C字符串蛮好的数组中的第一个C字符串。
我的想法是,我incorrecly传递结构,我想知道它传递给函数的正确方法。

it will print the first C string in the array of c strings just fine. My thoughts are that I am passing the structure incorrecly and I would like to know the correct way to pass it to the function.

编辑:

int builtin_cmd(char **argv);
int main()
{
    char *argv[128];
    //put 'quit' into argv[0]..
    printf("%s\n", argv[0]); //prints 'quit'
    builtin_cmd(argv);
}
int builtin_cmd(char **argv)
{
    printf("%s\n", argv[0]); //prints nothing
}

问题是,再一次,我不能似乎得到ARGV到函数。它还会编译没有错误或警告。

The problem is, again, that I cant seem to get argv into the function. It also compiles with no errors or warnings.

推荐答案

您正试图性格特征指针数组传递给函数,所以你的函数declratation应 builtin_cmd(字符* argv的[]) 。这里的一个样本为例,通过指针数组的功能

You are trying to pass an array of charecter pointers to an function so your function declratation should be builtin_cmd(char* argv[]).Here's an sample example to pass array of pointers to an function

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void fill_strings(char *str[], int nstrings)
{
    int i;
    for ( i=0; i < nstrings; i++)
        strcpy(str[i], "hello world");
}

void print_strings(char *str[], int nstrings)
{
    int i;
    for (i=0; i < nstrings; i++)
        printf("string %d: %s\n", i, str[i]);
}

int main(void)
{
    char *index[10];
    int i;
    for(i=0; i<10; i++)
    {
        index[i] = malloc(20);
    }
    fill_strings(index, 10);
    print_strings(index, 10);

    return 0;
}

这篇关于我该如何正确地传递这个数组c字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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