|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
||||
|
||||
|
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
|
||||
|
||||
|
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. ![]() |
|
#3
|
||||
|
||||
|
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. |
|
#4
|
||||
|
||||
|
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.
|
![]() |
| Viewing: Dev Shed Forums > Programming Languages > C Programming > Converting int to char * |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|