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
The both programs have undefined behavior.
For starters you may not use empty braces to initialize an array in C (opposite to C++).
Secondly, the function
atoiexpects a pointer to a string. However you are using a single characternIf you want for example to add digits of the entered number then write
Also you need guarantee that the length of the entered string is not greater than 10