Avoiding pointer arithmetic when using char ** argv

When trying to print the first command line argument:

std::cout << argv[0] << std::endl; 

clang-tidy gives a warning:

warning: 'do not use pointer arithmetic' from [cppcoreguidelines-pro-bounds-pointer-arithmetic]

Is there an alternative way to use argv values ​​without using pointer arithmetic? Doesn't have access to char** any reasonable method that would have to use pointer arithmetic?

I appreciate that there are some specialized functions for handling command line arguments, but they seem too heavy for the simple output of a single argument.

I write in c++ using the clang compiler and creating with cmake .

+5
source share
1 answer

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

Pointers should refer only to individual objects, and the arithmetic of pointers is fragile and is easily mistaken. span<T> is a border-tested, safe type for accessing data arrays.

So yes:

Is there an alternative way to use argv values ​​without using pointer arithmetic? Does char ** get accessed by any reasonable method that should use pointer arithmetic?

You are absolutely right. However, the manual aims to hide this pointer arithmetic, allowing the helper class to perform border checks before doing arithmetic. You can build span<char*> from argv and argc .

+5
source

Source: https://habr.com/ru/post/1270929/


All Articles