InfoSecNoob
InfoSecNoob

Reputation: 37

stdlib.h not working as intended with atoi() function

In my program, I'm using the atoi() function to extract an int from argv. When I use:

#include <stdlib.h>

I get the following error:

cachesim.c:20: warning: passing argument 1 of ‘atoi’ from incompatible pointer type

However, if I do not include the stdlib.h I receive no error at all and my code functions properly. Why is this?

#include <stdlib.h>
#include <stdio.h>
int main(int argc, int **argv) {
    if (argc == 0){
        int blk = 32;
        int i;
        for (i = 1; i < argc; i++) {
            if (strcmp(argv[i], "-b") == 0) {
                if (i + 1 <= argc - 1)
                    blk = atoi(argv[i+1]);
            }
        }
    }
}

Upvotes: 0

Views: 1790

Answers (2)

GriffinG
GriffinG

Reputation: 662

argv is supposed to be a character array, you have to read the characters and then convert them into an int.

Also, what is:

if(argc == 0)

If you have no arguments? That should never even be possible because the program name is in passed as an argument.

See:

What does int argc, char *argv[] mean?

You also didn't declare int blk in the correct scope, when you leave that if(argc == 0) statement, the variable blk will disappear.

Upvotes: 0

ouah
ouah

Reputation: 145919

Change:

main(int argc, int **argv){ 

to

int main(int argc, char *argv[]){

Your former declaration is not an acceptable declaration for main and atoi requires a parameter of type char *.

Upvotes: 3

Related Questions