如何使用指向struct字段的指针? [英] How to intilize a pointer to a struct field ?

查看:176
本文介绍了如何使用指向struct字段的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用指向结构字段的指针



我尝试过:



how to intilize a pointer to a struct field

What I have tried:

typedef struct SVisitor
{
  char **room_name;
} Visitor;

typedef struct SChallengeRoom
{
   char *name;
} ChallengeRoom;
// i want to chane room_name in the first struct to name in the second sruct 
//i did something like this 
visitor_enter_room(ChallengeRoom *room, Visitor *visitor){
visitor->room_name=room->name
}

推荐答案

initizialation的主要状态应该是指针应为null。如果你需要一些内存,你必须分配所需的内存。



最佳做法是为每个结构分配自己的内存

The primary state of initizialation should of a pointer should be null. If you need some memory than you must allocate the needed memory.

Best practise is to allocated own memory for every struct.
visitor_enter_room(ChallengeRoom *room, Visitor *visitor) {
visitor->room_name = malloc( strlen(room->name) + 1 );//allocate memory
strcpy( visitor->room_name,room->name); // copy string
}



如果你已经完成了那个记忆你必须使用免费清理!!!

提示:你也可以使用strdup和free。

Google了解更多细节和示例代码。


If you are done with that memory you must use free to cleanup!!!
Tip: you can also work with strdup and free.
Google for further details and sample code.


这篇关于如何使用指向struct字段的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆