可以初始化/分配结构指针吗? [英] Possible to initialize/assign a struct pointer?
问题描述
假设我具有以下结构和两个版本来对其进行初始化:
Let's say I have the following struct and two versions to initialize it:
#include <stdio.h>
typedef struct Car *CarPtr;
typedef struct Car {
const char* name;
unsigned int price;
} Car;
int main(void) {
Car ford = {
.name = "Ford F-150",
.price = 25000
};
print_struct(&ford);
// is this possible to do in a single assignment?
CarPtr jeep = {
.name = "Jeep",
.price = 40000
};
print_struct(jeep);
}
第二个版本可以直接使用吗?还是我需要按照以下方式做些事情:
Is the second version possible to do directly? Or do I need to do something along the lines of:
CarPtr jeep;
jeep->name = "Jeep";
jeep->price = 40000;
或者直接初始化 CarPtr
类型的正确方法是什么?
Or what's the proper way to initialize the CarPtr
type directly?
推荐答案
除空指针外,指针需要指向存在的对象(可以是已分配但尚未填充的内存).您可以使用复合文字定义指针并将其初始化为同时创建的对象:
Pointers, other than null pointers, need to point to objects that exist (which can be memory that has been allocated but not yet filled in). You can define a pointer and initialize it to an object you create at the same time, using a compound literal:
CarPtr jeep = & (Car) { .name = "Jeep", .price = 40000 };
这是一种特殊的语法,括号中的类型名称与定义中的包含初始化程序的花括号相同.(不是演员.)
This is a special syntax, with the type name in parentheses followed by braces containing initializers just as in a definition. (It is not a cast.)
您还可以将复合文字或它的地址直接传递给函数:
You can also pass a compound literal or its address directly to a function:
print_struct(& (Car) { .name = "Jeep", .price = 40000 });
但是,这具有有限的用途,因为如果在函数内部完成此操作,则该对象是临时的.它的生存期仅在当前函数执行持续的时间内持续.您可以在函数外部使用复合文字,然后该文字才能持续执行所有程序.使用复合文字之前,您应该对复合文字的属性有一般的了解和认识.
However, this has limited uses, as, if this is done inside a function, the object is temporary; its lifetime lasts only as long as the current function execution lasts. You can use a compound literal outside a function, and then it lasts for all of program execution. You should have a general understanding and awareness of the properties of compound literals before using them.
这篇关于可以初始化/分配结构指针吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!