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=1
和a1.b=5
的值时,得到a1.e=0
和a1.d=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