#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2013
    Posts
    2
    Rep Power
    0

    Problem with casting int to char* (C language not C++)


    Hi guys,
    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 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? ...
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2013
    Location
    Saint-Petersburg, Russia
    Posts
    236
    Rep Power
    28
    I fear you are misguided. ch_number_of_rev really is char[] which is the same as char*.

    However, in this line you wrote the ch_number_of_rev with a typo.
    CodeAbbey - programming problems for novice coders
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2013
    Posts
    2
    Rep Power
    0
    Originally Posted by rodiongork
    I fear you are misguided. ch_number_of_rev really is char[] which is the same as char*.

    However, in this line you wrote the ch_number_of_rev with a typo.

    It maybe is the same but function strcat() can't take it cos it need strcat(char*,char*)

    So I cant put array of chars into this function.. for example "790" and not '7','9','0' ...I hope you understand me... my english isn't perfect...
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,837
    Rep Power
    480

    Really messed up. Super wrong.


    version = "0.";

    "0." is a constant.

    strcat(constant, more_data);

    overwrites memory you shouldn't be accessing this way.

    You need

    char array[BIG];
    strcpy(array, "0.");
    strcat(array, little);


    Except that of course you should use strncpy and strncat to avoid buffer overruns. I don't feel like looking them up right now to get the order of arguments correct. You should.


    Another possibility:

    sprintf(array, "0.%d", the_integer);
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo