user1709294
user1709294

Reputation: 1805

C - Make variable INT as Char * for strcat

I'm trying to make a char * with the char representing an integer. So I have this so far

int x;
for(x=0;x<12;x++){
    cp->name=strcat(tp->name, (char *)x);
}

name is char* The problem is the x portion. I get segmentation fault and I'm assuming it's because it can't access the address the contents of x and cast it as char *

any tips on this?

Thanks

Upvotes: 1

Views: 4445

Answers (3)

tangrs
tangrs

Reputation: 9940

By casting x to a char *, you're telling the compiler, "I know what I'm doing. Treat x as an address and pass it to strcat"

Because x contains an integer between 0 and 12, strcat is trying to access a char array at address at that number. Because that address in memory most likely doesn't belong to you, you're getting a segfault.

You'll need sprintf or snprintf for getting a string representation of the integer.

For example:

int x;
for(x=0;x<12;x++){
    char buffer[16];
    snprintf(buffer, sizeof(buffer), "%d", x);
    cp->name=strcat(tp->name, buffer);
}

Upvotes: 3

Lie Ryan
Lie Ryan

Reputation: 64923

In C, you can use sprintf(str,"%d",x); or in C++ stringstream std::ostringstream oss; oss << tp->name << x;. If you have no qualms with using non-standard function, you can also use non-standard itoa() function.

Upvotes: 0

Alexey Frunze
Alexey Frunze

Reputation: 62106

You need to explicitly convert the number in x into a string (=array of chars). You can't do this by a mere type cast.

Using sprintf() is probably the easiest way:

int x;
for (x = 0; x < 12; x++)
    sprintf(tp->name + strlen(tp->name), "%d", x);

Needless to say, tp->name must have enough space in it and it must be '\0'-terminated before you do the above.

Upvotes: 0

Related Questions