【问题标题】:Remove last character, then concatenate two strings删除最后一个字符,然后连接两个字符串
【发布时间】:2016-02-29 09:25:03
【问题描述】:

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

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的大小是否正确等

【问题讨论】:

  • 这取决于server_files_directory 是什么。例如,修改字符串字面量是非法的。
  • char *server_files_directory;
  • 取消引用具有自动存储持续时间或NULL的未初始化变量是非法的。
  • 假设 server_files_directory 没问题并且已经初始化。
  • 我担心的是:删除部分是否正确,生成的fullPath的大小是否正确等

标签: c arrays string char concatenation


【解决方案1】:

这是不可接受的,因为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);

【讨论】:

  • @ajfbiw.s 我认为你应该考虑读一本关于C 的书,然后去寻找pointers 的段落。
  • 该示例存在缺陷。你能看出来吗?
猜你喜欢
  • 1970-01-01
  • 2015-09-01
  • 2017-02-22
  • 2016-01-21
  • 2011-12-15
  • 1970-01-01
  • 2021-01-18
  • 2015-08-22
相关资源
最近更新 更多