简体   繁体   English

C - 为strcat创建变量INT作为Char *

[英]C - Make variable INT as Char * for strcat

I'm trying to make a char * with the char representing an integer. 我正在尝试使用表示整数的char来生成char *。 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. name是char *问题是x部分。 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 * 我得到分段错误,我假设它是因为它无法访问地址x的内容并将其转换为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 " 通过将x转换为char * ,您告诉编译器,“我知道我在做什么。将x视为地址并将其传递给strcat

Because x contains an integer between 0 and 12, strcat is trying to access a char array at address at that number. 因为x包含0到12之间的整数,所以strcat尝试访问该数字的地址处的char数组。 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. 你需要sprintfsnprintf来获取整数的字符串表示。

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 ). 您需要将x的数字显式转换为字符串(= chars数组)。 You can't do this by a mere type cast. 你不能仅仅通过类型转换来做到这一点。

Using sprintf() is probably the easiest way: 使用sprintf()可能是最简单的方法:

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. 不用说, tp->name必须有足够的空间,并且在执行上述操作之前必须将'\\0'终止。

In C, you can use sprintf(str,"%d",x) ; 在C中,您可以使用sprintf(str,"%d",x) ; or in C++ stringstream std::ostringstream oss; oss << tp->name << x; 或者在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. 如果您对使用非标准功能没有疑虑,您也可以使用非标准的itoa()函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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