sprintf

Started by
2 comments, last by olle55 21 years, 7 months ago
Hello! I am trying to "convert" a integer to a string so i can print it with TextOut(); However, when i compile, i dont get any errors, but the program terminates imediatly. It runs fine however if i comment the sprintf stuff. This is how im doing it.
  
// the integer i want to make a string of.

int a_int = 5;

// the charstring.

char *a_char;

// this is how im trying to do it. i have included stdio.h


sprintf(a_char, "%s", a_int);

// this however makes my program terminate, but if i understand the docs right, this is the way to do it! =(


  
Thanks in advance!
Advertisement
hi olle

you must allocate memory for your string
a_char = (char *) malloc (16); // reserves 16 bytes which is sufficient  


then use
sprintf(a_char,"%d",a_int);  


see sprintf (msdn)

dont forget to "free(a_char);"

[edited by - diego_rodriguez on September 10, 2002 11:12:34 AM]
It seems you don''t allocate any memory for your
temporary string a_char. A pointer without
allocation is useless.

If you don''t need a_char in the rest of your
program, you''d better define a array of char
like this :


int i = 123;
char temp_str[80]; // change 80 with the number of characters you need
sprintf( temps_str, "the INT i want to disPLAY: %i", i);

conclusion: DONT USE A CHAR*, use a CHAR buffer instead!

This topic is closed to new replies.

Advertisement