c - malloc 然后 strcpy 与将其设置为等于字符串之间的区别
问题描述
假设我有
struct student
{
char* first_name;
};
typedef struct
{
struct student name;
} Person;
char* first_name_of_someone = "John";
为什么我必须先 malloc 然后 strcpy 才能将 John 放入 first_name?为什么我不能像这样分配它
Person* person = malloc(sizeof(Person));
struct student s;
s.first_name = "John";
person->name = s;
解决方案
如果您事先知道要复制什么值,那么您就不需要malloc
s.first_name = "John";
如果您要知道在运行时要复制什么值怎么办?在这种情况下,您需要malloc
and strcpy
。
fgets(tempbuf, sizeof tempbuf, stdin);
s.first_name = malloc(somelength);
strcpy(s.first_name, tempbuf);
或者
s.first_name = tempbuf;
在后一种情况下first_name
,将始终指向存储在tempbuf
.
推荐阅读
- java - 制作一个游戏,您单击一个圆圈并出现一个新圆圈,但不知道如何使圆圈成为按钮
- swift - TimeInterval 类型的编码和解码枚举
- javascript - react app中令牌过期时如何注销用户
- python - 如何使用python中的字典从具有多个值的键中访问单个值
- amazon-web-services - AWS CDK:如何在另一个账户中访问 VPC
- ios - 是否可以创建在 Objective C 中手动开发的核心数据实体的快速扩展?
- python - 使用列号访问熊猫中的列并按条件过滤行
- node.js - 地址已在使用中... Node 上的 Linux Web 服务器
- c - C语言中读写并发进程的行为
- python - 如何遍历数据框中的每一行