# getopt, argv += optind



## graudeejs (Feb 2, 2013)

I was reading getopt(3) manual (and also check in ls(1) source) and I saw one line of C code, that I couldn't understand how (more importantly why it works).

After processing command line arguments you can see this code

```
argc -= optind;
argv += optind;
```
First line is obvious.

On second line, however
*argv* is array of pointers to *char**.
*optind* is index to the next *argv* argument.

So why this code works?


----------



## kpa (Feb 2, 2013)

It works because argv is a pointer (pointer and arrays are almost the same thing in C) to a vector of pointers. Once you have used one argument you increment the argv pointer to point to the next pointer in the vector and so on.


----------



## fonz (Feb 2, 2013)

graudeejs said:
			
		

> ```
> argv += optind;
> ```
> *argv* is array of pointers to *char**.
> ...


First: argv is an array of pointers to char, not an array of pointers to char[red]***[/red]. That would be something like (either works)
	
	



```
char **argv[]
char ***argv
```
.

Second: adding a positive integer value to a pointer (or array) increases the memory location it points to by the size of the pointer (which is typically an int or long int but it depends on the architecture). In other words: argv points to argv[0], argv+3 points to argv[3] and of course argv+optind points to the first argument no longer parsed by getopt.


----------



## graudeejs (Feb 2, 2013)

fonz said:
			
		

> Second: adding a positive integer value to a pointer (or array) increases the memory location it points to by the size of the pointer



Thanks. I either for got that, or didn't knew about it.
Haven't been coding C for 2+ years 

And yes, you are right about argv, my statement was very wrong.


----------

