Filling up array type char*

Hi, I'm trying to pass char* and char* arr[] to a function where they will be parsed...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
  #define MAX_LINE 80

void parseInput(char* args[], char* input)
{
    int i = 0;
    char* token = strtok(input, " ");
    while (token != NULL) {
        args[i] = token;
        printf("%d - %s\n", i, args[i]);
        token = strtok(NULL, " ");
        i++;
    }
}

int main(void)
{
    char *history;
    char inputBuffer[MAX_LINE];
    char *args[MAX_LINE/2+1];
    int should_run = 1, i;

    while(should_run)
    {
        printf("osh> ");
        fflush(stdout);
        fgets(inputBuffer, MAX_LINE, stdin);

        //lets stop when quit or exit is written
        if(!strcmp(inputBuffer, "quit\n") || !strcmp(inputBuffer, "exit\n"))
        {
            should_run = 0;
            break;
        }

        printf("Read from input: %s\n", inputBuffer);
        printf("%d\n", strlen(inputBuffer));

        parseInput(&args[MAX_LINE/2+1], inputBuffer);
    }
    //when I here try this, it works
    args[0] = "zero";
    args[1] = "one"; //etc


    for(i = 0; i<((MAX_LINE/2)+1); i++)
        printf("%d - %s\n", i, args[i]);

    return 0;
}


It's failing and I'm not sure why. It seems to me that I have passed the pointers correctly.
Seeing your error messages would help us help you.

But line 38 and lines 41 and 42 look to be part of the problem.
I added 41 and 42 to demonstrate how it should be done.

Yes, the problem is on 38 and on top where that function is declared and defined.

1
2
C:\***\console\main.c|8|note: expected 'char **' but argument is of type 'char *'|
C:\***\console\main.c|41|warning: passing argument 1 of 'parseInput' from incompatible pointer type [enabled by default]|


1
2
3
4
5
char inputBuffer[MAX_LINE];
char *args[MAX_LINE/2+1];
int no_of_arguments = 0;

parseInput(args[MAX_LINE/2+1], inputBuffer, &no_of_arguments);


1
2
3
4
5
6
7
8
9
10
11
12
void parseInput(char* args[], char* input, int* argument_no)
{
    int i = 0;
    char* token = strtok(input, " ");
    printf("%s\n", token);
    while (token != NULL) {
        strcpy(args[i], token);
        printf("%d - %s\n", i, args[i]);
        token = strtok(NULL, " ");
        i++;
    }
}
Last edited on
First why is args declared as a pointer and not an array of C-string?

Where are you allocating memory for that pointer?

Second in your function call you are passing accessing your array out of bounds.

args is array of arrays. It would have been the same if I wrote char** args.
args is array of arrays.

No it is not an array of arrays until you allocate memory for that pointer.

It would have been the same if I wrote char** args.

No, that is a pointer to a pointer to char, neither pointer is initialized.

Topic archived. No new replies allowed.