Thread: Making a const char * out of argv

  1. #1
    Registered User
    Join Date
    Feb 2011
    Posts
    144

    Making a const char * out of argv

    Hello, everyone. Here is the barebones of my code. I am trying to iterate the strings pointed to by argv, to parse options etc. My code never modifies the argv array, nor the strings pointed to by it, and I want the compiler to enforce that (and to provide an optimization hint to the compiler).

    Code:
    void fn(int argc, const char *argv[])
    {
    }
    
    int main(int argc, char *argv[])
    {
      fn(argc, argv);
    }
    This compiles with gcc 5.4.0 with a warning:

    Code:
    test.c: In function ‘main’:
    test.c:7:12: warning: passing argument 2 of ‘fn’ from incompatible pointer type [-Wincompatible-pointer-types]
       fn(argc, argv);
                ^
    test.c:1:6: note: expected ‘const char **’ but argument is of type ‘char **’
     void fn(int argc, const char *argv[])
    I can use (const char **) when passing argv, but that feels like a sledgehammer that can mask problems. What's the correct solution?

    Richard

  2. #2
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    Question 11.10

    The "solution" is to use the cast.

  3. #3
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    Quote Originally Posted by Richardcavell View Post
    I can use (const char **) when passing argv, but that feels like a sledgehammer that can mask problems. What's the correct solution?
    That's strange, the compiler shouldn't complain about implicit casting from pointer to const pointer... Well, I guess the way to be rid of that warning is to either explicitly disable it or cast the pointer to const.

    EDIT: Oh, as I see at that page, a double pointer is treated differently.
    Last edited by GReaper; 08-10-2017 at 01:21 PM.
    Devoted my life to programming...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 04-20-2011, 01:19 PM
  2. what's the mean of : char* const* argv ?
    By Rede in forum C Programming
    Replies: 4
    Last Post: 03-10-2010, 01:20 AM
  3. Replies: 3
    Last Post: 11-15-2009, 04:57 AM
  4. Difference between const char * and char const *
    By explorecpp in forum C Programming
    Replies: 4
    Last Post: 08-09-2008, 04:48 AM
  5. Replies: 7
    Last Post: 04-28-2008, 09:20 AM

Tags for this Thread