首页 > 解决方案 > GCC 不会因为 strcpy() 和 sizeof() 而编译干净

问题描述

当我strncpy()用这样的未初始化字符串调用时

strncpy(person->name, string, sizeof(person->name));

然后用-Walland编译-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;

标签: carrays

解决方案


推荐阅读