使用atoi函数将字符串转换为整数时出现分段错误

问题描述 投票:0回答:1

虽然尝试使用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;
}

c atoi
1个回答
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数组的指针。

atoi()的MAN页面中,语法为:

int atoi(const char *nptr);

建议:替换:

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

with:

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

将输出数组s[]中每个字符的ASCII值。例如,ASCII值“ 1”为49。

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

© www.soinside.com 2019 - 2024. All rights reserved.