Search code examples
carrayscharstrtoull

strtoull use properly in C


So I have a string like this:

char numbers[] = "123,125,10000000,22222222222]"

This is an example, there can be lots more of numbers in the array but it will certainly end with a ].

So now I need to convert it to an array of unsigned long longs. I know I could use strtoull() but it takes 3 arguments and I don't know how to use that second argument. Also I would like to know how I can make my array have the right length. I would like to have my code look like this, but not in pseudocode but in C:

char numbers[] // string of numbers seperated by , and at the end ]
unsigned long long arr[length] // get the correct length
for(int i = 0; i < length; i++){
    arr[i]=strtoull(numbers,???,10)// pass correct arguments
}

Is this possible in C to do it like that?


Solution

  • The second argument to strtoull is a pointer to a char * that will receive a pointer to the first character after the number in the string argument. The third argument is the base to use for conversion. Base 0 allows for a 0x prefix to specify hexadecimal conversion and a 0 prefix to specify octal, just like the C integer literals.

    You can parse your line this way:

    extern char numbers[]; // string of numbers separated by , and at the end ]
    unsigned long long arr[length] // get the correct length
    char *p = numbers;
    int i;
    for (i = 0; i < length; i++) {
        char *endp;
        if (*p == ']') {
            /* end of the list */
            break;
        }
        errno = 0;  // clear errno
        arr[i] = strtoull(p, &endp, 10);
        if (endp == p) {
            /* number cannot be converted.
               return value was zero
               you might want to report this error
            */
            break;
        }
        if (errno != 0) {
            /* overflow detected during conversion.
               value was limited to ULLONG_MAX.
               you could report this as well.
             */
             break;
        }
        if (*p == ',') {
            /* skip the delimiter */
            p++;
        }
    }
    // i is the count of numbers that were successfully parsed,
    //   which can be less than len