1

This is my code in C that reads data from input:

#include<string.h>
#define MAX 3
char a[MAX];
char b[MAX];
void ReadFirstNumber();
void ReadSecondNumber();
int lb,la=0;
void main()
{
    ReadFirstNumber();
    ReadSecondNumber();
    printf("\n First Number > %d %d %d \n",a[0],a[1],a[2]);
    printf(" Second Number >  %d %d %d \n",b[0],b[1],b[2]);
}
void ReadFirstNumber()
{
    int i=0;
    printf("Enter the first number:");
    scanf("%s", a);
    la=strlen(a)-1;
    for(i=0;i<=la;i++)
    {
        a[i] = a[i] -48;
    }
}
void ReadSecondNumber()
{
    int j=0;
    printf("Enter the Second number:");
    scanf("%s", b);
    lb=strlen(b)-1;
    for(j=0;j<=lb;j++)
    {
        b[j] = b[j] -48;
    }
}

input first number example: 123
input second number example: 456 or any 3-digit number

//output
First Number    **0**23
Second Number   456 

The output for first number is 023

The first character is Zero! but the output for second number is ok.

When I comment out second function //ReadSecondNumber(); it worked perfectly!

3
  • 7
    The MAX define is not large enough to contain three-char strings, (null terminator), so UB 'cos exceeding the bounds of arrays. Commented Feb 2, 2015 at 21:22
  • ok thanks your response is perfect! Commented Feb 2, 2015 at 21:29
  • void main() is also undefined behaviour, use int main(void) instead. Commented Feb 2, 2015 at 22:00

1 Answer 1

3

You failed to allow enough space for the null terminator char that scanf("%s",...) writes at the end of 'strings'. Increase the value of the MAX #define. You may as well put in something sanely larger, eg 32.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.