以下代碼在 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
關于功能strtoul,
unsigned long int strtoul(const char *str, char **endptr, int base)
(請參閱下面的更新說明。)
str在and中傳遞對同一物件的參考是否正確endptr?或者它沒有在我臉上爆炸只是一個幸運的巧合?
參考手冊中stdlib沒有提到(例如)。
更新:
- 在評論和答案中,它參考了 C 標準。這是其草案的鏈接:ISO N2310。
- 在本檔案中,
strtoul函式的第一個引數被呼叫nptr,而不是str這個問題中使用的名稱。下面的答案和討論大多使用nptr. - Section 6.7.3.1 contains the formal definition of the type qualifier
restrict. - Section 7.22.1.3 contains the description of
strtoul()
uj5u.com熱心網友回復:
除了restrict限定詞之外,strtoulC 2018 7.22.1.4 中的檔案和 7.1.4 中的一般使用標準庫的檔案都沒有宣告禁止*endptr指向相同的記憶體nptr(其中endptr和nptr是第二個和的第一個引數strtoul),也沒有說明在這種情況下規范的任何放寬(例如,沒有斷言如果這種條件成立,行為將是未定義的)。
所以我們只需要考慮restrict限定符。strtoul被宣告為unsigned long int strtoul(const char * restrict nptr, char ** restrict endptr, int base)。使用restrict6.7.3.1 中的正式定義并首先考慮restricton nptr,6.7.3.1 4 告訴我們,如果通過任何方式修改了 或 any 指向的記憶體nptr,則用于訪問它的所有其他左值都應基于nptr. 滿足此條件是因為strtoul不會修改nptr指向的字串。
考慮到restricton endptr,我們觀察到它指向的記憶體確實被修改了,因為它strtoul存盤了一個值到該記憶體。然后 6.7.3.1 4 要求用于訪問該記憶體的所有其他左值都應基于endptr. 滿足此條件是因為strtoul不訪問表示msg除 through 之外的位元組endptr。
因此,即使使用strtoul(msg, &msg, 10).
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/442177.html
標籤:c implementation c-standard-library strtoul
上一篇:了解macOS的分段錯誤錯誤
