简体   繁体   中英

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

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);
}

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.

In C, you can use sprintf(str,"%d",x) ; or in C++ stringstream std::ostringstream oss; oss << tp->name << x; 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM