Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid pointer arithmetic when using char** argv

People also ask

Is it char * argv or char * argv?

char** argv is the same as char* argv[] because in the second case "the name of the array is a pointer to the first element in the array".

Why is argv a pointer?

The first element of the array, argv[0] , is a pointer to the character array that contains the program name or invocation name of the program that is being run from the command line. argv[1] indicates the first argument passed to the program, argv[2] the second argument, and so on.

What is the point of pointer arithmetic?

One usually uses pointer arithmetic when they want to get a pointer again. To get a pointer while using an array index: you are 1) calculating the pointer offset, then 2) getting the value at that memory location, then 3) you have to use & to get the address again.


From clang-tidy - cppcoreguidelines-pro-bounds-pointer-arithmetic:

Pointers should only refer to single objects, and pointer arithmetic is fragile and easy to get wrong. span<T> is a bounds-checked, safe type for accessing arrays of data.

So yes:

Is there an alternative way to use the values of argv without using pointer arithmetic? Isn't accessing a char** by any sensible method going to have to use pointer arithmetic?

You're entirely correct. However, the guideline is about hiding that pointer arithmetic, letting a helper class do bounds checks before performing the arithmetic. You can construct a span<char*> from argv and argc. E.g. in C++20 you would write:

auto args = std::span(argv, size_t(argc));

and then use args instead of argv.