c - GCC 不会因为 strcpy() 和 sizeof() 而编译干净
问题描述
当我strncpy()
用这样的未初始化字符串调用时
strncpy(person->name, string, sizeof(person->name));
然后用-Wall
and编译-Werror
,我看到这个错误:
src/parser.c:18:35: error: argument to ‘sizeof’ in ‘strncpy’ call is the same expression as the destination; did you mean to provide an explicit length? [-Werror=sizeof-pointer-memaccess]
strncpy(person->name, string, sizeof(person->name));
我看到其他一些帖子提到了 C 中的数组衰减,在这种情况下是一样的吗?strncpy()
那么在这个函数中使用的正确方法是什么?
编辑:首先,我malloc'd
是结构体和字符串,然后我调用了strncpy()
. 这是结构的样子:
typedef struct {
char *name;
int age;
int phone_num;
} person_t;
解决方案
推荐阅读
- android - 除了检查 sdk 路径和卸载 avast 之外,如何解决“无法定位 adb 问题”
- javascript - 在 Node.js 中调用我的一个函数时,程序首先调用 emitHookFactory 并陷入无限循环
- java - 使用 Spring Boot 从 Kafka 队列消费时获取序列化异常
- python - 将 Hessian 定义为零
- javascript - 如何通过列表向下键或向上键以触发对事件侦听器内项目的关注?
- c++ - malloc - 运行时内存指针类型分配
- c - 为什么这个while循环没有中断?
- javascript - 如何使用 babel cli 构建整个项目结构
- mfc - IFileDialog 或 SHBrowseForFolder:如何打开显示“计算机”的内容,最好不显示左侧的桌面等?
- c++ - 本地 std::bernoulli_distribution 如何创建准确分布的数据?