简体   繁体   English

使用 atoi function 将字符串转换为 integer 时出现分段错误

[英]Segmentation fault error while converting string to integer using atoi function

While am trying to convert a string to an integer using atoi function, I do not get any output.在尝试使用 atoi function 将字符串转换为 integer 时,我没有得到任何 output。 Upon debugging, it shows segmentation fault error in the line t=atoi(s[i]);调试时,在t=atoi(s[i]);行显示分段错误错误。 Here's the code for your reference:这是供您参考的代码:

#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;
}

when compiling, always enable the warnings, then fix those warnings:编译时,始终启用警告,然后修复这些警告:

Running the posted code through the gcc compiler results in:通过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.

in other words, this statement:换句话说,这个声明:

t = atoi(s[i]);

is passing a single character to the function: atoi() But, atoi() expects to be passed a pointer to a char array.正在将单个字符传递给 function: atoi()但是, atoi()期望传递一个指向 char 数组的指针。

From the MAN page for atoi() , the syntax is:atoi()的 MAN 页面中,语法为:

int atoi(const char *nptr);

suggest: replacing:建议:替换:

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

with:和:

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

Which will output the ASCII value of each of the characters in the array s[] .其中将 output 数组s[]中每个字符的 ASCII 值。 As an example the ASCII value of '1' is 49.例如,“1”的 ASCII 值是 49。

Note that modern compilers output warns about failing to check the returned value from C library functions.请注意,现代编译器 output 会警告未能检查 C 库函数的返回值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM