Double char pointer Operations

Suppose I have char **argv

.

First, how can I print all lines in argv

? I tried the following:

char *temp;
temp = *argv; // Now points to the first string?
while (temp != NULL) {
    printf("%s ", temp);
    temp++;
}

      

Here, when temp

incremented, it only skips one character. Why is this happening? I know it argv

is an array that contains points. Each pointer points to an array char*

. If so, why doesn't it work? I know that since it temp

has a type char

, incrementing that pointer will increment it by 1

char (or byte). If so, how can I increment the pointer to the next array and print that string?

+3


source to share


5 answers


It only skips one character because it temp

is a pointer to char

. By adding one of these, you are telling the compiler to move the pointer to point to the next one char

in memory.

argv

- an array of pointers. What you need to do is go to the next pointer at each iteration. Something like:



char **temp = argv;  // temp is a pointer to a *pointer*, not a pointer to a *char*
while (*temp != NULL) {
    printf("%s ", *temp);
    temp++;
}

      

+6


source


You need to increase argv

, not *argv

. With a local copy, it looks like this:



for (char ** p = argv; *p; ++p)      // or "*p != NULL"
{
    char * temp = *p;                // now points to the first string!
    printf("%s ", temp);             // or just "printf("%s", *p);"
}

      

+6


source


First, you need to understand what it is char** argv

. It is an array of pointers to char. The pointers in this array do not have to be somewhere near each other in the address space. What you want is this:

char** temp;
temp = argv;
while(temp != argv + argc) {
    printf("%s ", temp);
    temp++;
}

      

You must have a pointer to the first element of the array to pointers to char. Add instead.

+1


source


You need to increase argv

not *argv

. Note that if yours argv

is a function parameter main

it can be changed and you can use it like this:

    while (*argv++) {
        printf("%s\n", *argv);
    }

      

0


source


what you probably want to do is:

char* a = argv[0];  // first arg
char* b = argv[1];  // second arg
char* c = argv[2];  // third arg

      

which is equivalent to this:

char* a = *(argv + 0);
char* b = *(argv + 1);
char* c = *(argv + 2);

      

which you would like to summarize in a loop.

0


source







All Articles