MABC
MABC

Reputation: 595

Program crash when atoi(str) is performed

I dont know why this code keep crashing:

int main(void)
{
char input[13];
int i;

fgets(input,sizeof(input),stdin);
i = atoi(input[0]);

return 0;
}

If i type '1' (without quotes) the program crash. Compiler is mingw.

Upvotes: 0

Views: 1838

Answers (2)

sgwizdak
sgwizdak

Reputation: 101

It crashes because atoi expects a char *. When you give it an char in this case, there's nothing to tell the compiler that the value provided isn't really a pointer to something else. And so the program ultimately crashes.

You can change this to either:

i = atoi(input);

or

i = atoi(&input[0]);

Upvotes: 3

Paul R
Paul R

Reputation: 212979

atoi requires a char * (C string) not a single char. Change:

i = atoi(input[0]);

to:

i = atoi(input);

Also note that you should always compile with warnings enabled (e.g. gcc -Wall ...) - if you had done this then the compiler would have helpfully pointed out your mistake for you.

Upvotes: 2

Related Questions