【问题标题】:Passing char * into struct将 char * 传递给结构
【发布时间】:2019-09-19 11:58:46
【问题描述】:

所以,我有一个结构成员 char*,我想在分配节点内存后对其进行初始化。但是,这种方法给我带来了 Seg Fault。 笔记。是的,我想要一个 infoPtr。请原谅任何语法错误,这些不是我要解决的问题。我想要的只是正确地将一个 char 字符串传递给 name。

struct Info{
    char *name;
}
typedef struct Info *infoPtr;
int main(void){
    enter("google");
}
void enter(char *name){
    infoPtr* info=(infoPtr)malloc(sizeof(infoPtr));
    info->name=strup(name);
}

【问题讨论】:

标签: c struct


【解决方案1】:

这里

typedef struct Info *infoPtr;

infoPtrstruct Info* 类型,这个

infoPtr* info=(infoPtr)malloc(sizeof(infoPtr)); /* info will be of struct Info** type */

应该是

infoPtr info = malloc(sizeof(*infoPtr)); /* typecasting is not required */

旁注,typedef 指针不是很好的做法,请阅读Is it a good idea to typedef pointers?

这里也有

info->name=strup(name);

您想使用 strdup() 而不是 strup() 表示例如

info->name=strdup(name);

回答你的问题我想要的只是正确地将一个 char 字符串传递给 name ?是的,你将参数传递给 enter() 的方式是正确的,除了 typedefing struct pointer .并传递字符串文字google like

enter("google");

并定义enter() 喜欢

void enter(char *name){ /* Its correct */
  /* play with name */
}

【讨论】:

  • 这再次说明了为什么您永远不应该typedef 指针。
  • 当然,这意味着 OP 提供的代码从未成功编译,因此永远不会产生段错误,所以谁知道这是否是真正让他们绊倒的问题。
  • 别忘了free()每个strdup()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-01
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-09
相关资源
最近更新 更多