-4

I have a little problem with casting int to char* (string)... is it even possible in C? I'll try to explain why i need this.

I can cast int to char but I need cast int to char*.

I had a int varriable (int number_of_revisions) and I need convert this number of revisions to char * becouse I need create a name of file and the number of revision is part of the name.... so there is part of code for better imagination of this problem.

int number_of_revision = 970; // 970 just for example
char * version;
char * new_name;
char ch_number_of_rev[4];

version = "0.";
itoa(number_of_revision,ch_number_of_rev,10);
//strcat(version, ch_num_o_rev ); // doesn't work becouse ch_number_of_rev is char and strcat requires char*

please I need quick help... Have anybody any idea how to do it? ...

this
  • 5,229
  • 1
  • 22
  • 51
user3036674
  • 143
  • 2
  • 3
  • 7

2 Answers2

4

but I need cast int to char*

Casting only changes the type - it does not change the value within the variable. If you need to convert an int to array of chars (i.e. a string) then use sprintf or snprintf:

char* buffer = ... allocate a buffer ...
int value = 970;
sprintf(buffer, "%d", value);

Converting int to string in c

Also, you have not allocated any memory for version - use malloc and allocate some memory.

Community
  • 1
  • 1
Sadique
  • 22,572
  • 7
  • 65
  • 91
1

strcat here won't work because you haven't allocated any space to store the result in. Your version is probably in read-only memory anyway, so you'd get a segfault, otherwise you'll get memory corruption. So make sure to allocate enough space for it, e.g. by using

char version[10] = "0.";

You may want to read up on pointers first, though.

creichen
  • 1,728
  • 9
  • 16
  • Ok I allocated memory for "version" and nothing changed.... – user3036674 Nov 27 '13 at 06:54
  • Ok I finaly solve this.. thanks guys for help. There is what I did: char version[40]; char buffer[4]; int value = 970; sprintf(buffer, "%d", value); strcat(version, buffer ); – user3036674 Nov 27 '13 at 07:06