[英]Concatenating two strings with strncat
I would like to concatenate two strings, adding a new random character, using strncat() so basically I'm doing this: 我想连接两个字符串,添加一个新的随机字符,使用strncat()所以基本上我这样做:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define CHARACTER_RANGE 25
#define INITIAL_CHARACTER 65
int main(){
char male[32] = "A", female[32] = "B", new_letter[1], new_name[32];
srand(time(NULL));
strcpy(new_name, male);
strncat(new_name, female, sizeof(new_name) - strlen(new_name) - 1);
new_letter[0]= (rand() % CHARACTER_RANGE) + INITIAL_CHARACTER;
strncat(new_name, new_letter, sizeof(new_name) - strlen(new_name) - 1);
printf("New string is %s!\n", new_name);
return 0;
}
In case of new letter is F expected result should be: 如果新信是F,预期结果应该是:
New string is ABF!
Instead, the result is: 相反,结果是:
New string is ABFAB!
I can't figure out why this happens. 我无法弄清楚为什么会这样。
The second call to strncat
is incorrect: 第二次调用
strncat
是不正确的:
strncat(new_name, new_letter, sizeof(new_name) - strlen(new_name) - 1);
new_letter
is not a proper C string, as it does not have a null terminator, nor is there any space to store it after the letter. new_letter
不是一个合适的C字符串,因为它没有空终止符,也没有空格来存储它。 If sizeof(new_name) - strlen(new_name) - 1
is greater than 1
, the behavior is undefined. 如果
sizeof(new_name) - strlen(new_name) - 1
大于1
,则行为未定义。
Here is a corrected version: 这是一个更正版本:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define CHARACTER_RANGE 25
#define INITIAL_CHARACTER 65
int main() {
char male[32] = "A", female[32] = "B", new_letter[2], new_name[32];
srand(time(NULL));
strcpy(new_name, male);
strncat(new_name, female, sizeof(new_name) - strlen(new_name) - 1);
new_letter[0] = (rand() % CHARACTER_RANGE) + INITIAL_CHARACTER;
new_letter[1] = '\0';
strncat(new_name, new_letter, sizeof(new_name) - strlen(new_name) - 1);
printf("New string is %s!\n", new_name);
return 0;
}
Note however that the call to strcpy
is performed without a protection. 但请注意,对
strcpy
是在没有保护的情况下执行的。 In this particular example, the source string fits into the destination buffer, but for a more generic approach, there is a simpler method to construct strings within fixed array boundaries with snprintf
: 在此特定示例中,源字符串适合目标缓冲区,但对于更通用的方法,有一种更简单的方法可以使用
snprintf
在固定数组边界内构造字符串:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define CHARACTER_RANGE 26
#define INITIAL_CHARACTER 'A'
int main() {
char male[] = "A", female[] = "B", new_name[32];
srand(time(NULL));
snprintf(new_name, sizeof new_name, "%s%c",
rand() % 2 ? female : male,
rand() % CHARACTER_RANGE + INITIAL_CHARACTER);
printf("New string is %s!\n", new_name);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.