【问题标题】:Segmentation fault error while converting string to integer using atoi function使用 atoi 函数将字符串转换为整数时出现分段错误
【发布时间】:2020-08-21 15:58:00
【问题描述】:

当我尝试使用 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;
}

【问题讨论】:

  • 您将 character 传递给atoi,而不是字符串地址。试试t = atoi(s + i); 应该有一个编译器警告——不要忽略它们。
  • s[i] 是一个字符。但atoi 需要一个字符串。您可以使用atoi(&amp;s[i]) 读取以i 开头的数字。
  • 注意:在读取带有atoi 的数字后,您应该跳过 s[i] 后面的所有数字,因为您刚刚处理了它们。除了i++,还有更多工作要做。
  • int x = atoi(s); printf("%d\n", x);替换整个while()循环
  • 非常感谢@Weather Vane @ Paul Ogilvie @ chux - 恢复 Monica。这对我有用。

标签: c atoi


【解决方案1】:

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

通过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 数组的指针。

atoi() 的 MAN 页面,语法是:

int atoi(const char *nptr);

建议:替换:

t = atoi(s[i]);
printf("%d\n",t);

与:

printf( "%d\n", s[i] );

这将输出数组s[] 中每个字符的ASCII 值。例如,'1' 的 ASCII 值是 49。

请注意,现代编译器的输出会警告未能检查 C 库函数的返回值。

【讨论】:

  • 非常感谢@user3629249。
  • @user36 在printf( "%d\n", s[i] ); 中使用%c 而不是%d 更好?
猜你喜欢
  • 1970-01-01
  • 2014-12-16
  • 1970-01-01
  • 1970-01-01
  • 2015-09-03
  • 2021-11-23
  • 1970-01-01
  • 2020-02-16
  • 2018-05-05
相关资源
最近更新 更多