Caio Schnepper
Caio Schnepper

Reputation: 21

Function atoi returns wrong number

I wrote the following code:

#include <stdio.h>
#include <stdlib.h>

void main (void) {

//------------------------ Variaveis------------------------//
    char num[2];
    int aux1, aux2, aux3;

//------------------------Parte grafica---------------------//
    printf ("Escreva um numero de 0 a 99: ");
    scanf ("%s", &num);
    printf("\nEste numero por extenso eh: ");

//-------------------------Conversão------------------------//
    aux1 = atoi(num);
    aux2 = atoi(&num[0]);
    aux3 = atoi(&num[1]);

Don't mind the language, the point is, if you type a number like "56" for scanf to read for example, aux2 gets the value of "56" instead of "5" that I wanted, and aux3 gets the value of "6" which is actually what I expected. What is wrong with aux2?

Upvotes: 1

Views: 502

Answers (2)

Pras
Pras

Reputation: 4044

You have undefined behavior as you dont have space of null terminator when you enter 2 digit numeric value as string in char num[3];

Change it to char num[3] and take input as:

scanf ("%2s", num);

When you print

printf("%d %d %d\n",aux1,aux2,aux3); // for input 56

You would get 56 56 6 The reason is num and &num[0] are same, they point to same address where as &num[1] would point to next address so you get 6 there

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726539

Once you fix undefined behavior by adding space for null terminator, let's consider behavior of your program.

What is wrong with aux2?

Since atoi considers the whole string, aux2 is the same as aux, because it's the string starting at '5' and continuing to '\0'.

If you wanted to get the individual digits, use subtraction of '0':

int aux2 = num[0] - '0';
int aux3 = num[1] - '0';

Make sure that num has exactly two characters, and both characters are digits.

Upvotes: 3

Related Questions