10

Why am I getting an error when using the atoi() function?

#include <stdio.h>
#include <string.h>
int main()
{
    char s1[10], s2[10];
    int x=5, y=6, z;
    sprintf(s1, "%d", x);
    sprintf(s2, "%d", y);
    strcat(s1, s2);
    z = atoi(s1);
    printf("%d, %s", z, s1);
    return 0;
}
Neuron
  • 5,141
  • 5
  • 38
  • 59
Chandra Sekhar Bala
  • 190
  • 1
  • 1
  • 12
  • 3
    Since `atoi()` is declared in ``, as `man atoi` would tell you, it is a reasonable error (and it should, indeed, be treated as an error, not just a warning). – Jonathan Leffler Oct 09 '20 at 19:25
  • Aside: for a 32-bit `int` the `char s1[10],s2[10];` arrays are too small to be safe over the whole range of values. There can be 10 digits, a minus sign, and a string terminator, total 12. So define them as `char s1[16], s2[16];` and don't be tight. – Weather Vane Oct 09 '20 at 19:51
  • Then how is atoi() without including stdlib.h compiles and runs? Can anyone explain ? – elig Dec 02 '21 at 23:47

1 Answers1

29
#include <stdlib.h>

Will fix it.