darksky
darksky

Reputation: 21039

Double Pointer char Operations

Assume I have char **argv.

First, how can I print out all the strings in argv? I tried the following:

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

In here, when temp is incremented, it only skips one character. Why is that happening? I know that argv is an array that holds points. Each pointer, points to an array of char*. If so, why isn't this working? I know that since temp is of type char, incrementing that pointer would increment it by 1 char (or byte). If so, how can I increment the pointer into the next array and print that string out?

Upvotes: 5

Views: 27843

Answers (5)

Preet Kukreti
Preet Kukreti

Reputation: 8617

what you probably want to do is this:

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 then want to generalise into a loop.

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477368

You need to increment argv, not *argv. With a local copy, this looks like so:

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

Upvotes: 6

ouah
ouah

Reputation: 145899

You have to increment argv not *argv. Note that if your argv is the parameter of the main function it is modifiable and you can use it like this:

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

Upvotes: 0

Collin
Collin

Reputation: 12287

First, you need to understand what char** argv is. It is an array of pointers to char. The pointers in this array don't necessarily reside anywhere near eachother in the address space. What you want is this:

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

You need to have a pointer to the first element of the array to pointers to char. Increment that instead.

Upvotes: 1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272657

It skips only one character because temp is a pointer to a char. By adding one, you're telling the compiler to move the pointer on to point at the next char in memory.

argv is an array of pointers. What you need to do is move on to the next pointer on 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++;
}

Upvotes: 7

Related Questions