Question

Here's the prototype for the C standard library routine strtol:

long int strtol(const char* str, char** endptr, int base);

Typical usage:

const char* str = "123a";
char* endptr;
long int value = strtol(str, &endptr, 10);

if (*endptr)
  // Do something
else
  // Do something else

Why is it done this way? Why not pass the address of a local variable?

Example:

long int strtol(const char* str, char* endptr, int base);

Usage:

const char* str = "123a";
char end;
long int value = strtol(str, &end, 10);

if (end)
  // Do something
else
  // Do something else

I'm sure there is a logical reason for this design decision, but I don't quite see it.

Was it helpful?

Solution

It is using pointer to pointer for second parameter because it allows the caller to know exact position in string where parsing has stopped - and may be used to continue parsing the stream using some other method. Also, it permits to completely ignore it by supplying NULL.

Note that your proposed schema does not possess these useful properties.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top