Thread: strtol and const char*

  1. #1
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Ireland
    Posts
    8,446

    strtol and const char*

    Code:
    void validate(int *arg, const char *optarg, ...)
    {
        errno = 0;
        char **invalid = NULL;
        *arg = (int) strtol(optarg, invalid, 10);
    I'm having trouble with the above code. The standard says that invalid will only be updated if it is not NULL (7.22.1.4(5) and 7.22.1.4(7)).

    However I can't seem to be able to define a working pointer to optarg:

    const char **invalid = &optarg -> fails on the strtol call. invalid is expected to be a char **.

    char **invalid = &optarg -> is obviously wrong.

    The alternative is to drop the const qualifier from the validate function definition. But I'd rather it stayed. How can I solve this?
    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  2. #2
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    It's normally used like this.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    void validate(int *arg, const char *optarg) {
        char *endptr = NULL;
        *arg = (int) strtol(optarg, &endptr, 10);
        printf("%p %p\n", optarg, endptr);
    }
    
    int main(void) {
        int n = 0;
        validate(&n, "123xyz");
        printf("%d\n", n);
        return 0;
    }
    Last edited by algorism; 10-31-2016 at 03:57 PM. Reason: changed "invalid" to "endptr"

  3. #3
    Nasal Demon Xupicor's Avatar
    Join Date
    Sep 2010
    Location
    Poland
    Posts
    179
    algorism beat me to it. Yep, you just provide it an address of a proper pointer if you want the function to change it. Otherwise you just pass in NULL there and the function knows it's not a proper address and thus won't try to write to it. So what the standard says is you can do what algorism did, or: result = strtol(s, NULL, 10);

  4. #4
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Ireland
    Posts
    8,446
    Makes all sense. Thank you.
    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 04-20-2011, 01:19 PM
  2. Replies: 3
    Last Post: 11-15-2009, 04:57 AM
  3. Difference between const char * and char const *
    By explorecpp in forum C Programming
    Replies: 4
    Last Post: 08-09-2008, 04:48 AM
  4. Replies: 7
    Last Post: 04-28-2008, 09:20 AM
  5. Assigning Const Char*s, Char*s, and Char[]s to wach other
    By Inquirer in forum Linux Programming
    Replies: 1
    Last Post: 04-29-2003, 10:52 PM

Tags for this Thread