简体   繁体   English

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

[英]Remove last character, then concatenate two strings

Is below an acceptable way of removing the last char from the first string, then concatenating it with a second string? 下面是从第一个字符串中删除最后一个字符,然后将其与第二个字符串连接的一种可接受的方法吗?

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

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

Let's assume server_files_directory is fine (char *) and has been initialized. 假设server_files_directory很好(char *)并且已经初始化。

What I'm worried about is: if the removing part is correct and if the size of the resulting fullPath is correct, etc. 我担心的是:如果删除的部分正确,并且生成的fullPath的大小正确,等等。

This is not acceptable because there is no space to store terminating null character in fullPath . 这是不可接受的,因为在fullPath没有空间存储终止空字符。

The declaration should be (add +1 ) 声明应为(add +1

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

UPDATE: alternative way without breaking what is pointed by server_files_directory : 更新:不破坏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);

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

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