The following code runs well under gcc 11.2.1:
// test.c
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char **argv){
char *msg;
unsigned int val;
msg = "1024 2048 4096 13";
while(*msg != '\0'){
val = strtoul(msg, &msg, 10);
printf("%u\n",val);
}
return 0;
}
gcc -Wall -o test.bin test.c
$ ./test.bin
1024
2048
4096
13
Regarding the function strtoul
,
unsigned long int strtoul(const char *str, char **endptr, int base)
(See notes on Update below.)
Is it correct to pass references to the same object in str
and endptr
? Or is it just a lucky coincidence that it did not explode in my face?
The reference manuals to stdlib
do not mention that (for example).
Update:
- In the comments and answer it is referenced the C standard. Here a link to its draft: ISO N2310.
- In this document, the first argument of the
strtoul
function is callednptr
as opposed tostr
which is the name used in this question. The answer and discussion below mostly usesnptr
. - Section 6.7.3.1 contains the formal definition of the type qualifier
restrict
. - Section 7.22.1.3 contains the description of
strtoul()