getting an int from optarg

121 Views Asked by At

Im trying to get an int from the optarg from the c modifier in my code, but i can't get to it, I tried to cast it but it wasn't possible, so I investigated and found this atoi() function suposed to get an int from a string, but its still printing the error "format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘int (*)()". This is the code (it's not finished):

    if(strcmp(argv[1], "crea") == 0){
        if(argc>7 || argc<6){
            fprintf(stderr, "Número de argumentos incorrecto, el uso es : ./misala crea -f [nombre archivo] -c [capacidad] [-o]\n");
            exit(1);
        }
        int c;
        while((c=getopt(argc, argv, "f:oc:n:a:"))!=-1){
            switch (c){
                case 'f':
                    f_flag = 1;
                    ruta = malloc(sizeof(char)*strlen(optarg));
                    strcpy(ruta, optarg);
                    break;
                case 'o':
                    o_flag = 1;
                    break;
                case 'c':
                    c_flag = 1;
                    int capacidad;
//here I want to get an int from optarg to store in variable capacidad
                    capacidad = atoi(optarg);
                    break;
                case '?':
                    fprintf(stderr, "Modificador no válido");
                    break;
                
            }
        }
//here the error is triggered (only with capacidad, ruta is propertly working)
        printf("RUTA = %s, CAPACIDAD = %d\n", ruta, capacidad);
    }
}


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

    ejecuta_funcion(argc, argv);
    
}```
1

There are 1 best solutions below

2
Allan Wind On

You need to define the variable int capacidad; in scope where the printf() statement has access to it. Prefer strtol() to atoi() as the latter doesn't have support proper error handling. Don't use the same name for a variable and a function. They are in the same name space.