#1
  1. Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2003
    Posts
    15
    Rep Power
    0

    Converting int to char *


    Could someone please explain why the statement:

    int intVar = 255;
    printf("\nintVar = ", (char *) intVar);

    produces the output:

    intVar =

    I can guess as to why this is a problem since the data types are totally incompatible, but the compiler doesn't produce any errors (I'm using Visual C++.) I'm probobly missing something obvious since I just started programming with C++, so could someone tell me how to accomplish what I'm trying to do properly?
  2. #2
  3. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,593
    Rep Power
    4207
    Change your printf statement to:

    printf("\nintVar = %d", intVar);

    The %d tells the printf() function to print the variable as an integer. There's no need to type-cast an intvar to a char pointer. :)
  4. #3
  5. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,091
    Rep Power
    2222
    FYI & for your future debugging:

    You normally want the number of format variables (my term, I forget what's official; eg %d) to equal the number of arguments that follow the format string. Failure to do so will result two different kinds of problems:

    1. if you have more arguments than format variables, then the last arguments will simply be ignored. Your problem is an example of this.

    2. If you have more format variables than arguments -- eg,
    printf("x=%d, y=%d, z=%d\n",x,y);
    -- then it will try to fill that third format variable with whatever "follows" y in memory, AKA "garbage".

    Back to the example:
    Code:
    x = 1;
    y = 2;
    z = 3;
    
    printf("x=%d, y=%d, z=%d\n",x,y);
    will probably produce something like:
    x=1, x=2, z=-43256893

    It's always a surprise to get a result like that. So when you get really wild formatted output, particularly in the last fields, the number of arguments and of format variables should be the first thing you check.

    Lesson gained from personal experience.
  6. #4
  7. Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2003
    Posts
    15
    Rep Power
    0
    Thanks for the help. I think I'm going to read through the source of stdio.h to learn a bit more about it before I start to get too comfortable with it's functions.

IMN logo majestic logo threadwatch logo seochat tools logo