c语言 struct中的字符串类型成员变量不建议使用char指针定义

比如下面的代码:

struct pnames {
    char * first;
    char * last;
};

struct pnames tt;

scanf("Please enter the first name: %s", tt.first);
scanf("Please enter the last name: %s", tt.last);

由于定义了struct pnames类型的变量tt,但是并没有初始化该变量。所以first,last的值有可能会指向内存中的任何区域。后边如果scanf对first,last指向的内存区域做修改,可能导致意想不到的问题。而使用char数组则没有问题,比如:

struct pnames {
    char first[20];
    char last[20];
};

struct pnames tt;

scanf("Please enter the first name: %s", tt.first);
scanf("Please enter the last name: %s", tt.last);

此时定义了变量tt,就会为first,last分配固定的空间,用来保存用户通过scanf的输入。这样保证了安全性。

有一种情况我们可以使用在struct中使用字符指针,就是我们可以结合malloc(),来根据用户输入的字符长度申请相应的同等大小内存来保存。比如:

struct pnames {
    char * first;
    char * last;
};

struct pnames tt;

char first[20];
char last[20];

scanf("Please enter the first name: %s", first);
scanf("Please enter the last name: %s", last);

tt.first = (char *) malloc(strlen(first)+1);
tt.last = (char *) malloc(strlen(last)+1);

但是这样做,一定要用free去释放内存,否则程序退出时会导致内存泄漏。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值