[Courses] [C] question about concatenating ints to strings (simple question)

Laurel Fan laurel at sdf.lonestar.org
Fri Dec 6 18:04:21 EST 2002


On Fri, Dec 06, 2002 at 07:27:02PM -0500, Morgon Kanter wrote:
> how would I cast an integer value to a character before passing it to 
> stringcat?

strcat takes a string (pointer to a character) not a character.  It is
possible to cast a pointer to an integer to a pointer to a character,
for example:

int i;
char *p = (char *)(&i);

However, casting pointers to types that are different sizes (int and
char are usually different sizes) is generally a bad idea, and
probably not what you want in this case.

If I wanted to append a single character to a string, I would find the
end of the string, then set the character there to the appropriate
value:

int number = 1;
char digit = 1 + '0';
int current_number_length = strlen(current_number); 
if (current_number_length + 1 < max_current_number_length) {
    current_number[current_number_length] = digit;
    current_number[current_number_length + 1] = '\0';
} else {
    /* number is too long for string */
}

If I wanted to write a number to the end of a string, I would find the
end of the string, then do some pointer arithmetic and use sprintf
(or, more robustly, snprintf):

int number = 1;
int current_number_length = strlen(current_number); 
int available_length = max_current_number_length - current_number_length;
if (available_length > 1) {
    char * starting_point = current_number + current_number_length; 
    snprintf(starting_point, available_length, "%d", number);
} else {
    /* number is too long for string */
}

> For example:
> 
> int a = 1;
> char current_number[5];
> 
> strcat(current_number, (char *)a); <---- this line gives SIGSEGV (segfault)
> 
> (char) and no cast also sends segfault...how do I fix this problem :P It's 
> been plaguing me since I started this (exercise 3 lesson 13)

When you cast an integer to a pointer, you do not create a pointer to
the integer, you create a pointer to that address.  In your example,
you are giving strcat a pointer to the address 1.  There is nothing
good at the address 1, so it segfaults.

Casting is not smart at all.  If you try to cast an integer to a
string, you do not get a string containing characters representing
that integer.  Casting is telling the compiler "I said that was an
integer before, but I changed my mind and now you should act as if it
is a char *".

-- 
laurel at sdf.lonestar.org
http://dreadnought.gorgorg.org



More information about the Courses mailing list