[英]Segmentation fault error while converting string to integer using atoi function
在嘗試使用 atoi function 將字符串轉換為 integer 時,我沒有得到任何 output。 調試時,在t=atoi(s[i]);
行顯示分段錯誤錯誤。 這是供您參考的代碼:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char s[100];
int i=0,t;
printf("Enter: ");
fgets(s,100,stdin);
while(s[i]!='\0')
{
if(s[i]>='1' && s[i]<='9')
{
t = atoi(s[i]);
printf("%d\n",t);
}
i++;
}
return 0;
}
編譯時,始終啟用警告,然后修復這些警告:
通過gcc
編譯器運行發布的代碼會導致:
gcc -O1 -ggdb -Wall -Wextra -Wconversion -pedantic -std=gnu11 -c "untitled2.c" -I. (in directory: /home/richard/Documents/forum)
untitled2.c: In function ‘main’:
untitled2.c:14:16: warning: passing argument 1 of ‘atoi’ makes pointer from integer without a cast [-Wint-conversion]
t = atoi(s[i]);
^
In file included from /usr/include/features.h:424:0,
from /usr/include/x86_64-linux-gnu/bits/libc-header-start.h:33,
from /usr/include/stdio.h:27,
from untitled2.c:1:
/usr/include/stdlib.h:361:1: note: expected ‘const char *’ but argument is of type ‘char’
__NTH (atoi (const char *__nptr))
^
untitled2.c:9:3: warning: ignoring return value of ‘fgets’, declared with attribute warn_unused_result [-Wunused-result]
fgets(s,100,stdin);
^~~~~~~~~~~~~~~~~~
Compilation finished successfully.
換句話說,這個聲明:
t = atoi(s[i]);
正在將單個字符傳遞給 function: atoi()
但是, atoi()
期望傳遞一個指向 char 數組的指針。
在atoi()
的 MAN 頁面中,語法為:
int atoi(const char *nptr);
建議:替換:
t = atoi(s[i]);
printf("%d\n",t);
和:
printf( "%d\n", s[i] );
其中將 output 數組s[]
中每個字符的 ASCII 值。 例如,“1”的 ASCII 值是 49。
請注意,現代編譯器 output 會警告未能檢查 C 庫函數的返回值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.