Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why can argv use increment operator

it's in K&R's book

#include <stdio.h>

main(int argc, char *argv[])
{
    while (--argc > 0)
        printf("%s%s", *++argv, (argc > 1) > " " : "");
    printf("\n");
    return 0;
}

in this book, it says that array can't use increment or decrement operator, in this program ,"argv" should be an array's name, why it can use increment operator?

like image 267
Micheal Avatar asked May 26 '26 07:05

Micheal


2 Answers

The second parameter of the main

char *argv[]

is adjusted to pointer to the first element of the array. That is it has type

char **argv;

You may increase pointers.

Thus as initially argv (adjusted to pointer) points to the first element of an array of pointers to strings then ++argv points to the second element of the array and so on.

According to the C Standard (6.7.6.3 Function declarators (including prototypes))

  1. A declaration of a parameter as ‘‘array of type’’ shall be adjusted to ‘‘qualified pointer to type’’, where the type qualifiers (if any) are those specified within the [ and ] of the array type derivation.
like image 193
Vlad from Moscow Avatar answered May 27 '26 19:05

Vlad from Moscow


You are wrong. argv isn't an array. It is a pointer to a pointer to a char. Pointers can be incremented / decremented. And

main(int argc, char *argv[])

is the same as

main(int argc, char **argv)
like image 37
Spikatrix Avatar answered May 27 '26 20:05

Spikatrix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!