Search code examples
catoi

atoi from char * returning 0 in C


Very new to C so please bear with me. I have a function that takes in 3 char * variables, opcode, arg1 and arg2.

arg1 and arg2 can either be (1) a string containing the name of a variable holding an unsigned int, or (2) an actual integer.

Either way, I need to get the actual integer out. I am trying to use atoi so far but it seems to be returning 0 for the first case.

i.e.

sscanf(instruction, "%s %s %s", opcode, arg1, arg2);

sum = atoi(arg1) + atoi(arg2);

I can't post the entire code as it doesn't belong to me, but hopefully the above demonstration helps a little?


Solution

  • As I said in my comment, you can't expect to retrieve the value of a named variable at run-time, in C. Variable names are not something that is kept when the code runs, then it's pure machine code and all variables have been "cooked down" to memory addresses. The names are no longer around.

    The atoi() function converts a string holding an integer, such as "4711", into the actual value, 4711. That's all it does, it cannot retreive values "by name" in any way.

    If you want to have a mechanism to map variable names to values when the program runs, you are going to have to create that mechanism yourself, since the language does not have one. For instance, you could create some kind of array of structures that let you associate names with values, but that would of course require you to initialize that array.

    Something like this:

    int foo = 12;
    char *vname = "foo";
    
    print("the value of %s is %d\n", vname, get_variable_value(vname));
    

    simply is not going to happen in C, the function get_variable_value() cannot exist.