c - 您如何使用标头中的 strcat()连接两个指针指向的字符串?
问题描述
我正在尝试连接两个字符串以用作 fopen() 的路径。我有以下代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<malloc.h>
void main() {
char *inputchar = (char*)malloc(sizeof(char)), *absolutepath = (char*)malloc(sizeof(char));
FILE *filepointer;
gets(inputchar); //Name of the file that the user wants
absolutepath = "D:\\Files\\";
strcat(*inputchar, *absolutepath); //Error occurs here
filepointer = fopen(*inputchar, "r"); //Do I need to use the deference operator?
fclose(filepointer);
free(inputchar);
free(absolutepath);
}
strcat() 发生错误。那里发生什么了?
我必须在 fopen() 中对 inputchar 使用尊重运算符是否正确?
解决方案
这里有 3 件事要解决:
您为 inputchar 分配了恰好 1 个字符的空间。因此,获取长度超过 0 个字符的字符串会弄乱程序的内存。为什么长于 0 个字符?因为gets在字符串的末尾写了一个终止的0字符。所以分配更多的东西,例如
char *inputchar = (char*)malloc(256*sizeof(char));
absolutepath = "D:\\Files\\"; "D:\\files\\"
是一个字符串文字,其值由编译器确定。因此,您不需要使用 malloc 为该字符串分配空间。你可以说:char *absolutepath = "D:\\Files\\";
调用 strcat 时,您为其提供指针值,而不是字符串的第一个字符。所以你应该做
strcat(inputchar, absolutepath);
代替
strcat(*inputchar, *absolutepath);
我建议阅读一些初学者的 C 资源,例如这个http://www.learn-c.org/en/Strings可能对你有好处。
推荐阅读
- javascript - 无法将对象转换为原始值(discord.js)
- javascript - 如何从 javascript 函数中提取数据?
- pytorch - 在单个 GPU 上运行两个不同的独立 PyTorch 程序
- regex - 用于转换的 Grafana 正则表达式
- c# - 如何通过 Microsoft.Exchange.WebServices 获取 GAL id 并使用 FindPeople
- python - 使用符号解决问题:*:“符号”和“平等”不支持的操作数类型
- gekko - Gekko MPC 控制器 - 在每个时间步更新参数
- wordpress - Woocommerce 和 Yoast 产品搜索错误
- python - 如何知道我连接的麦克风是否被任何用户使用?(Python 或 Linux x84-64)
- android - 在flutter中使用in_app_review包?