以下是从第一个字符串中删除最后一个字符,然后将其与第二个字符串连接的可接受方法吗?
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 *) 并且已经初始化。
我担心的是:删除部分是否正确以及生成的全路径的大小是否正确等。
最佳答案
这是 Not Acceptable ,因为在 fullPath
中没有空间来存储终止空字符。
声明应该是(add +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);
关于c - 删除最后一个字符,然后连接两个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35695847/