Thread: Having trouble with atoi

  1. #1
    Registered User
    Join Date
    Jun 2008
    Posts
    20

    Having trouble with atoi

    I have a function that is returning a string that looks like this:

    Code:
    char* getstring(char choice)
    {
    
         does some stuff...
    
    return(mystring);
    }
    Then back in my main I have this:

    Code:
    .
    .
    tempstring = getstring(mychar);
    
    myinteger = atoi(tempstring);
    .
    .
    .
    The problem is that atoi keeps returning zero. After tempstring is returned from the function, it is a string which only contains digits, no letters or anything else, except for the null terminator at the end of the string.

    I have run the program with a breakpoint at the atoi line and I can see that "tempstring" contains an integer. I can read in the Locals box:

    "tempstring 0x0013fae8 "80" "

    after I step through the atoi line, tempstring is empty and the atoi has put a 0 into myinteger.

    I don't understand why this is happening. I have also tried using strtol in place of atoi, but with no luck.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Lemme guess, mystring is a local char array inside the getstring() function.

    You can't do this!
    The array goes out of scope (along with your data) as soon as you return.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Jun 2008
    Posts
    20
    Yeah that was the problem. Thank you!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 01-03-2007, 03:02 PM
  2. trouble scanning in... and link listing
    By panfilero in forum C Programming
    Replies: 14
    Last Post: 11-21-2005, 12:58 PM
  3. help with this
    By tyrantil in forum C Programming
    Replies: 18
    Last Post: 01-30-2005, 04:53 PM
  4. Problem with atoi in C
    By garagebrian in forum C Programming
    Replies: 5
    Last Post: 08-24-2004, 01:59 PM
  5. string to int conversion not using atoi()
    By linucksrox in forum C Programming
    Replies: 2
    Last Post: 05-19-2004, 12:17 AM