Thread: Dealing with ints that are in char array

  1. #1
    Registered User
    Join Date
    Nov 2005
    Posts
    145

    Dealing with ints that are in char array

    I have a char array that has both ints and letters in it.

    I'm trying to take two numbers from this array and add them together, but I presume, seeing as they are stored as characters, that I'm doing something silly like adding there ascii values together.

    How do I treat them as inegers? I tried calling the array using int string1[], but that didn't help.

    Obviously this is wrong...

    Code:
    int x;
    x = string2[1] + string3[1];

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >I'm doing something silly like adding there ascii values together.
    That's it exactly.

    >How do I treat them as inegers?
    You need to convert the strings to integers using a standard function like strtol or a handwritten routine that does the same thing.
    My best code is written with the delete key.

  3. #3
    Registered User
    Join Date
    Nov 2005
    Posts
    145
    I'm trying to use the function atoi for the time being, and amhaving problems:

    Code:
    int x = atoi(string2[1]);
    101 C:\Documents and Settings\Chrisss\My Documents\C\assembler.c [Warning] passing arg 1 of `atoi' makes pointer from integer without a cast

    Can anybody see the problem here?

  4. #4
    Registered User
    Join Date
    May 2006
    Posts
    903
    It would be easier to find the exact answer if we knew what type was string2 but my first guess is that string2 is a char*; thus, accessing its second parameter returns a char where-as atoi() is taking a char*.

  5. #5
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >I'm trying to use the function atoi for the time being
    Don't use atoi, it's very easy to bumble into the subtle problems without knowing it and invoke undefined behavior. strtol is much better.

    >Can anybody see the problem here?
    string2[i] is a character, not a character string. If you must use a slice (which are tricky even on a good day), do this:
    Code:
    int x = atoi ( &string2[i] );
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. newbie needs help with code
    By compudude86 in forum C Programming
    Replies: 6
    Last Post: 07-23-2006, 08:54 PM
  2. Personal Program that is making me go wtf?
    By Submeg in forum C Programming
    Replies: 20
    Last Post: 06-27-2006, 12:13 AM
  3. Creating 2D arrays on heap
    By sundeeptuteja in forum C++ Programming
    Replies: 6
    Last Post: 08-16-2002, 11:44 AM
  4. help with array of char and char **
    By Unregistered in forum C Programming
    Replies: 1
    Last Post: 04-20-2002, 02:23 PM
  5. Strings are V important...
    By NANO in forum C++ Programming
    Replies: 15
    Last Post: 04-14-2002, 11:57 AM