Question

I have some problems with an example of atoi() function from K&R C 2nd edition. Only characters from 0 to 9 should be used. But somewhere in the logic of my program I do something wrong.

So in there is this function:

#include <stdio.h>

int atoi(char s[]);

int main()
{
    int i;
    char ch;
    char co[50]; 
    int  ci[50];

    while(ch != EOF )
    {

        for(i=0;i<50-1 && (ch=getchar()) != EOF && ch != '\n';++i)
        {
            co[i] = ch;
            /*ci[i] = atoi(co[i]);*/ /*bugged*/
            ci[i] = atoi(co);
            printf("%d \n",ci[i]);
        }
        if(ch == '\n')
        {
            co[i] = '\n';
        }
        ++i;
        co[i] = '\0';
    }

    return(0);

}

/* as in the book: */
/* atoi: convert s to integer */

int atoi(char s[])
{
    int i, n;
    n = 0;
    for(i = 0; s[i] >= '0' && s[i] <= '9'; ++i)
    {
        n = 10 * n + (s[i] - '0');
    }

    return(n);
}

Here are the errors I'm getting:

|In function 'main':
19|warning: passing argument 1 of 'atoi' makes pointer from integer without a cast [enabled by default]
3|note: expected 'char *' but argument is of type 'char'
||=== Build finished: 0 errors, 1 warnings (0 minutes, 0 seconds) ===|
Was it helpful?

Solution 2

atoi(); function need pointer to string. char* that is the reason warning warning: passing argument 1 of 'atoi' makes pointer from integer without typecase

you declare co like: char co[50]; but calls atoi(co[i]); this is wrong,

notice it says int not char.

an example like:

atoi("1"); is valid but atoi('1'); not valid.

so even co is like "12345678" then atoi(co) correct but atoi(co[i]) not correct.

OTHER TIPS

The

(s[i] = '0')

should read

(s[i] - '0')

(note the minus instead of the equals sign).

This converts the characters '0'..'9' to the numeric values 0..9.

You are also not calling atoi() correctly. It takes a string, not a char. You should probably call it from outside the loop.

And ch isn't the right type (it should be int).

printf("%c = ",co[i]);
ci[i] = atoi(co[i]);
printf("%d \n",ci[i]);

You are trying to convert a char to int, but a char is an integer value. All you need is

printf("%c = %d\n", co[i], co[i]);

if what you want is the decimal value of the char. If what you're trying to do is convert an ASCII digit to an integer, then

printf("%c = %d\n", co[i], co[i] - '0');

will do.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top