我的程序中定义了几种数据类型,其中一种如下所示:
typedef struct {
char name[MAX_STR];
int value;
DataType dType;
} VarType;
我想使用我定义如下的函数“初始化”它:
void initVar(VarType *varPtr, char *name, int *val, DataType d)
{
varPtr = (VarType *) calloc(1,sizeof(VarType));
strcpy(varPtr->name, name);
varPtr->dType;
/* we have to store it differently depending on the type, be careful! */
if(d==C_INT_PTR)
varPtr->value = (int)(val);
else if(d==C_INT)
varPtr->value = *val;
/* NOTE THE FOLLOWING LINE */
printf("The variable name prints properly here: %s\n", varPtr->name);
}
最后,我想在代码的其他地方使用这些结构和方法,但是当我在使用字符串文字设置名称后检查名称时,它会打印出乱码,即使在initVar()
函数中打印得非常好。
/* let's store the variables we're gonna put in the frame */
VarType vars[3];
initVar(&vars[0], "num", &num, C_INT);
/* NOTE THE FOLLOWING LINE */
printf("This one prints like jibberish: %s\n",vars[0].name);
为什么它不再打印正确的字符串了?