首页 > 解决方案 > 使用 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;
}

标签: catoi

解决方案


编译时,始终启用警告,然后修复这些警告:

通过编译器运行发布的代码会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 库函数的返回值。


推荐阅读