C Language Single char declaration error after char array

90 Views Asked by At

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

1

There are 1 best solutions below

2
Vlad from Moscow On

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);