Why does strtol require a pointer to a pointer rather than a single pointer?

StackOverflow https://stackoverflow.com/questions/19201924

  •  30-06-2022
  •  | 
  •  

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.

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top