有没有一种语法上短的方法可以在堆上初始化结构指针?

Lav*_*air 1 c struct

当我有:

typedef struct {
    int id;
    char* key;
} some_pthread_arg;
Run Code Online (Sandbox Code Playgroud)

我可以说:

some_pthread_arg spa1 = 
  {
   .id = 123456, 
   .key = "Hello World!" // is it a problem, that i don't predefine the input size?
  };
Run Code Online (Sandbox Code Playgroud)

如果我想在这样的结构上初始化一个指针,我可以简单地:

some_pthread_arg *spa2 = &spa1;
Run Code Online (Sandbox Code Playgroud)

代替:

some_pthread_arg *spa2;
spa2->id = 123456;
spa2->key = "Hello World!"; // is it a problem, that i don't predefine the input size?
Run Code Online (Sandbox Code Playgroud)

但是如果我使用这个:

some_pthread_arg *spa2 = &spa1;
Run Code Online (Sandbox Code Playgroud)

我没有机会在堆上分配结构,而使用其他选项,我可以:

some_pthread_arg *spa2 = (some_pthread_arg *) malloc (sizeof(some_pthread_arg));
spa2->id = 123456;
spa2->key = "Hello World!"; // is it a problem, that i don't predefine the input size?
Run Code Online (Sandbox Code Playgroud)

长话短说,有什么类似的东西吗?

some_pthread_arg *spa2 = (some_pthread_arg *) malloc (sizeof(some_pthread_arg));
spa2 = 
  { 
   ->id = 123456,
   ->key = "Hello World" // is it a problem, that i don't predefine the input size?
  };
Run Code Online (Sandbox Code Playgroud)

Eri*_*hil 6

您可以使用复合文字:

some_pthread_arg *spa2 = malloc(sizeof *spa2);
if (!spa2) Handle error...
*spa2 = (some_pthread_arg) { .id = 12345, .key = "Hello, world!" };
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 在C中,您无需强制转换的结果malloc
  • malloc(sizeof *spa2)优于,malloc(sizeof(some_pthread_arg))因为,如果spa2更改的类型,一次编辑就足够了,而后者需要多次编辑,并且如果有人错过其中之一,就变成了错误。