#include <stdio.h>
#include <stdlib.h>
struct structAsFunctionParameter {
int a;
int b;
};
void initStructA(struct structAsFunctionParameter, int,int);
void initStruct(struct structAsFunctionParameter *, int,int);
struct structAsFunctionParameter initStructWithOutMallc(int, int);
struct structAsFunctionParameter* initStructWithinnerMalloc(int, int);
int main(int argc, char *argv[])
{
int a = 3,b =4;
struct structAsFunctionParameter structValue, *structPointer;
initStructA(structValue, a, b);
initStructB(structPointer, a, b);
//打印structValue和 structPointer的值
// printf("");
struct structAsFunctionParameter * structMalloced = (struct structAsFunctionParameter *)malloc(sizeof(struct structAsFunctionParameter));
initStructWithOutMallc(a, b);
initStructWithinnerMalloc(a, b);
return 0;
}
//初始化代码如下:
#include <stdio.h>
#include <stdlib.h>
struct structAsFunctionParameter
{
int a;
int b;
};
void initStructA(struct structAsFunctionParameter structAsFunctionParameterA, int a,int b)
{
structAsFunctionParameterA.a = a;
structAsFunctionParameterA.b = b;
}
void initStructB(struct structAsFunctionParameter *structAsFunctionParameterB, int a,int b)
{
structAsFunctionParameterB->a = a;
structAsFunctionParameterB->b = b;
}
struct structAsFunctionParameter initStructWithOutMallc(int a, int b)
{
struct structAsFunctionParameter structAsFunctionParameterS;
structAsFunctionParameterS.a = a;
structAsFunctionParameterS.b = b;
return structAsFunctionParameterS;
}
struct structAsFunctionParameter* initStructWithinnerMalloc(int a, int b)
{
struct structAsFunctionParameter *structAsFunctionParameterP =(structAsFunctionParameter*) malloc(sizeof(structAsFunctionParameter));
structAsFunctionParameterP->a = a ;
structAsFunctionParameterP->b = b ;
return structAsFunctionParameterP;
}
int main(int argc, char *argv[])
{
int a = 3,b =4;
struct structAsFunctionParameter structValue, *structPointer;
//structValue.a=0;
//structValue.b=0;
structPointer =(structAsFunctionParameter*) malloc(sizeof(structAsFunctionParameter));
//a = 1;//为了不混淆,再次赋值。
// b = 2;
initStructA(structValue, a, b); //值传递是会初始化失败的。
// a = 3;//为了不混淆,再次赋值。
// b = 4;
initStructB(structPointer, a, b);
//打印structValue和 structPointer的值
printf("the a of the structValue is %d,the b of the structValue is %d\n",structValue.a,structValue.b); //本行打印的值如果不赋初始值,将会出现乱码.
printf("the a of the structPointer is %d,the b of the structPointer is %d\n",structPointer->a,structPointer->b);
// a = 5;//为了不混淆,再次赋值。
// b = 6;
structValue = initStructWithOutMallc(a, b);
printf("the a of the structValue is %d,the b of the structValue is %d\n",structValue.a,structValue.b);
// a = 7;//为了不混淆,再次赋值。
// b = 8;
structPointer = initStructWithinnerMalloc(a, b);
printf("the a of the structPointer is %d,the b of the structPointer is %d\n",structPointer->a,structPointer->b);
return 0;
}
运行结果: