[英]Passing char * into struct
So, I have a struct member char* and I want to initialize it after allocating node memory .However,this method gets me a Seg Fault. 因此,我有一个结构成员char *,我想在分配节点内存后对其进行初始化。但是,此方法使我遇到了段故障。 Note.
注意。 YES, I want a infoPtr.
是的,我想要一个infoPtr。 Excuse any syntax errors, these are not the problem I am trying to solve .
请原谅任何语法错误,这些不是我要解决的问题。 ALL I want is to correctly pass a char string into name.
我想要的只是正确地将一个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);
}
Here 这里
typedef struct Info *infoPtr;
infoPtr
is of struct Info*
type, this infoPtr
是struct Info*
类型,此
infoPtr* info=(infoPtr)malloc(sizeof(infoPtr)); /* info will be of struct Info** type */
should be 应该
infoPtr info = malloc(sizeof(*infoPtr)); /* typecasting is not required */
Side note, its not considered as good practice to typedef
a pointer, do read Is it a good idea to typedef pointers? 旁注,将
typedef
指针视为不是一种好习惯,请阅读typedef指针是一个好主意吗?
Also here 也在这里
info->name=strup(name);
you wanted to use strdup()
instead of strup()
for eg 您想使用
strdup()
代替strup()
例如
info->name=strdup(name);
Coming to your question ALL I want is to correctly pass a char string into name ? 出现您的问题时, 我想要的就是正确地将一个char字符串传递给name吗? Yes the way you passed argument to
enter()
is correct except typedefing struct pointer . 是的,除了typedefing结构指针之外,您将参数传递给
enter()
是正确的。 And passing string literal google
like 并传递字符串文字
google
像
enter("google");
and defining enter()
like 并像这样定义
enter()
void enter(char *name){ /* Its correct */
/* play with name */
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.