我们可以在结构中有可以在C中动态初始化它们的字段吗?

问题描述 投票:-1回答:1
struct test{
    int a;
    int b;
    int e=a*c;
    int d= c( a, b );
}a1;

int c(int a,int b){
    return a*b;
}

在代码中,当我动态初始化a1.a=1a1.b=5的值时,得到a1.e=0a1.d=0。为什么这样?

c structure
1个回答
0
投票

不,您不能这样做。

此外,声明/初始化行int e=a*c没有意义。 c是一个功能。

请参见下面的完整示例:

#include <stdlib.h>
#include <stdio.h>

typedef struct test {
    int a;
    int b;
    int e=a*c;
    int d= c( a, b );
} test;

int c(int a,int b){
  return a*b;
}

int main(int argc, char** argv) {
  struct test* alpha = malloc(sizeof(struct test));

  printf("%d, %d, %d, %d", alpha.a, alpha.b, alpha.e, alpha.d);
}

gcc一起运行时,我得到:

lah.c:4:10: error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token
     int e=a*c;
          ^

我的建议是使用初始化函数:

test* init() {
  test* initialized_test = malloc(sizeof(test));
  initialized_test->e = initialized_test->a;
  initialized_test->d = c(initialized_test->a, initialized_test->b);
  return initialized_test;
}

然后,您的main函数将变为:

int main(int argc, char** argv) {
  test* alpha = init();

  printf("%d, %d, %d, %d\n", alpha->a, alpha->b, alpha->e, alpha->d);
}

实际上,这种模式非常流行,以至于在C ++中,它实际上被引入到new运算符中,以便在内存中创建新对象时调用构造函数(使用其他名称初始化函数)。另请参见https://www.tutorialspoint.com/cplusplus/cpp_constructor_destructor.htm

© www.soinside.com 2019 - 2024. All rights reserved.