c - 使用 atoi 函数将字符串转换为整数时出现分段错误
问题描述
在尝试使用 atoi 函数将字符串转换为整数时,我没有得到任何输出。调试时,它在行中显示分段错误错误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]);
正在将单个字符传递给函数:atoi()
但是,atoi()
期望传递一个指向 char 数组的指针。
在 MAN 页面中atoi()
,语法为:
int atoi(const char *nptr);
建议:替换:
t = atoi(s[i]);
printf("%d\n",t);
和:
printf( "%d\n", s[i] );
它将输出数组中每个字符的 ASCII 值s[]
。例如,“1”的 ASCII 值是 49。
请注意,现代编译器输出警告未能检查 C 库函数的返回值。
推荐阅读
- python-3.x - 将文本写入 tkinter 文本小部件重做
- signing - CN 在移动应用程序 apk 签名信息中代表什么?
- html - CSS:选择除一个以外的每个 div 元素
- jenkins - 我解决了詹金斯身份验证失败问题,但我不知道为什么?
- reactjs - 试图从表中删除一条记录,但它正在从 reacthook 页面中删除整个记录
- git - 当我找不到输出目标时撤消 git config 命令
- python - Visual Studio Code Django 调试断点未在视图和模板上触发
- c++ - bazel测试与直接执行
- database - psql:错误:致命:用户“Davinci”的密码验证失败
- javascript - 通过提示收号