删除最后一个字符,然后连接两个字符串

时间:2016-02-29 09:25:03

标签: c arrays string char concatenation

是否可以接受从第一个字符串中删除最后一个字符的可接受方式,然后将其与第二个字符串连接?

char *commandLinePath = server_files_directory;
commandLinePath[strlen(commandLinePath)-1] = 0;

char fullPath[strlen(commandLinePath) + strlen(requestPath)];
strcpy(fullPath, commandLinePath);
strcat(fullPath, requestPath);

假设server_files_directory很好(char *)并且已经初始化。

我担心的是:如果删除部分是正确的,以及生成的fullPath的大小是否正确等等。

1 个答案:

答案 0 :(得分:2)

这是不可接受的,因为没有空间来存储fullPath中的终止空字符。

声明应该是(添加+1

char fullPath[strlen(commandLinePath) + strlen(requestPath) + 1];

更新:替代方式,不会破坏server_files_directory指向的内容:

size_t len1 = strlen(commandLinePath);
size_t len2 = strlen(requestPath);
char fullPath[len1 + len2]; /* no +1 here because one character will be removed */
strcpy(fullPath, commandLinePath);
strcpy(fullPath + len1 - 1, requestPath);
相关问题