C Language Single char declaration error after char array

Viewed 75

There seems to be an overflow phenomenon depending on the declaration of n before and the declaration of n after Can you tell me the detailed reason?

Operable code

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

int main()
{
    int i, sum=0;
    char n, DNA[11]={};

    printf("용의자의 DNA정보를 입력하세요. :");
    scanf("%s", DNA);

    for(i=0; i<10; i++)
    {
        n = DNA[i];
        sum += atoi(&n);
    }

    if (sum%7 == 4)
        printf("범인");
    else
        printf("일반인");
}

Inoperable code

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

int main()
{
    int i, sum=0;
    char DNA[11]={}, n;

    printf("용의자의 DNA정보를 입력하세요. :");
    scanf("%s", DNA);

    for(i=0; i<10; i++)
    {
        n = DNA[i];
        sum += atoi(&n);
    }

    if (sum%7 == 4)
        printf("범인");
    else
        printf("일반인");

*Input conditions are up to 10 characters

2 Answers

The both programs have undefined behavior.

For starters you may not use empty braces to initialize an array in C (opposite to C++).

char n, DNA[11]={};

Secondly, the function atoi expects a pointer to a string. However you are using a single character n

sum += atoi(&n);

If you want for example to add digits of the entered number then write

for(i=0; DNA[i] != '\0'; i++)
{
    n = DNA[i];
    sum += n - '0';
}

Also you need guarantee that the length of the entered string is not greater than 10

scanf("%10s", DNA);

Rather than scan a string and assume the input is numeric, scan for single digits.
Accumulate the digits into the sum and into a numeric value.
Input will end with ten digits, a newline or a non-digit.

#include <stdio.h>
#include <limits.h>

int main ( void) {
    int i = 0;
    int sum = 0;
    int n = 0;
    int number = 0;
    char newline[2] = "";

    printf("DNA : ");
    fflush ( stdout);

    for ( i = 0; i < 10; i++) {
        if ( 1 == scanf ( "%1[\n]", newline)) { // scan for newline
            break;
        }
        if ( 1 == scanf ( "%1d", &n)) { // scan for one digit
            sum += n;
            if ( number < INT_MAX / 10 - n) {
                number *= 10;
                number += n;
            }
            else {
                fprintf ( stderr, "overflow\n");
                return 1;
            }
        }
        else {
            break;
        }
        scanf ( "%*[ \t\r\f\v]"); // scan and discard whitespace except newline
    }

    printf ( "number is %d\n", number);
    if ( sum % 7 == 4) {
        printf ( "remainder is 4\n");
    }
    else {
        printf("remainder is not 4\n");
    }
    return 0;
}
Related