Passing argv as const [duplicate]
Asked Answered
O

0

2

I want to pass argv to another function, and can do it with no problems when I define the function like this:

void function(char** argv);

and call it from main with:

function(argv);

However, I would like to keep everything const where possible (I don't actually plan to change argv, or the value of either of the pointers). My problem is that as soon as I add the keyword const anywhere to argv in the function declaration I get conversion errors, e.g. this code

void function(const char** argv);

gives the compile error:

error: invalid conversion from ‘const char**’ to ‘char* const*’ [-fpermissive]

I've tried putting const in different places and get similar errors. Is there a way to pass argv while keeping the contents and pointers all constant?

Oink answered 19/8, 2014 at 14:58 Comment(14)
Save yourself some headaches and store the parameters in a vector of strings and pass that instead. std::vector<std::string> arguments(argv + 1, argv + argc);Labroid
With what arguments are you trying to call the function when you get the warning? With which types are they declared?Tagmeme
@NeilKirk the function I'm passing to calls getopt which takes argv as an argument. If I make my own vector of strings I'd then have to convert it back to a char**, seems like more hassle than it's worth.Oink
@BugalugsNash Do you have any variable of type char* const* in your code? If yes, please add the corresponding code. Also does this answer help?Nib
@Tagmeme I've added that info in an editOink
@Nib there is no char* const* in my codeOink
Does the compiler say the error is in the call to function, and not something that function is calling? It kind of looks more like an error from within function.Kowalczyk
@Kowalczyk you are right, the error I reported was due to the code within the function (calling getopt with argv). I should have reported the first error, which occurred at the point where the function was called, and still occurs when the entire body of the function is deleted: error: invalid conversion from ‘char**’ to ‘const char**’ [-fpermissive]. This may be due to the problem @Nib linked to.Oink
@BugalugsNash getopt expects its argv to be char * const argv[], so you making your argv const char ** is incompatible.Kowalczyk
Can the arguments of main's signature in C++ have the unsiged and const qualifiers?Company
Why is main() argument argv of type char*[] rather than const char*[]?Company
What is the proper declaration of main?Company
There are lots of near-dup's, but the simple answer to this question is: int main( int argc, char * const argv[] )Company
I think you will benefit from seeing this, it really helps me understand.Shumaker

© 2022 - 2024 — McMap. All rights reserved.