How do I pass this array of c strings correctly? [closed]

隐身守侯 提交于 2019-12-02 14:41:07

You haven't shown how you initialize the array, and that's the crucial part.

#include <stdio.h>

static void builtin_cmd(char **argv)
{
     while (*argv != NULL)
         printf("%s\n", *argv++);
}

int main(void)
{
    char *argv[] = { "abc", "def", "ghi", NULL };
    builtin_cmd(argv);
    return 0;
}

This code uses a sentinel value, the null pointer, to mark the end of the data. The alternative is to pass the number of strings in the array as a separate argument. When you use int main(int argc, char **argv), you actually have both mechanisms in use; argv[argc] == NULL so there is the count and then sentinel value.

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

If you're passing your input on the command line you need to tell the compiler that you're using the parameters that are passed into main from the runtime.

int main(int argc, char **argv)
{

That should allow you to pass "quit" as the first parameter properly. Otherwise, as the others say, how you fill a "C vector" is important.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!