我有麻烦为结构中的指针赋值,我有这个结构:
tCliente cargarUno(int numC){
tCliente reg;
char letra;
int serv;
float mon;
reg.numCliente=numC;
fflush(stdin);
printf("\nIngrese Nombre del cliente:");
leeCad(reg.nombre,20);
printf("\nIngrese condicion de IVA(M-Monotributista,R-Responsable Inscripto,E- IVA Exento):");
fflush(stdin);
scanf("%c",&letra);
®->iva = &letra;
fflush(stdin);
printf("\nIngrese tipo de servicio(1 2 3):" );
scanf("%d",&serv);
®->tiposerv = &serv;
printf("\nIngrese monto a cobrar:");
scanf("%f",&mon);
®->monto= &mon;
return reg;
}
我有一个功能:
void mostrarUno(tCliente c){
printf("Numero del cliente:%d",c.numCliente);
printf("\n Nombre del cliente:%s",c.nombre);
printf("\n Condicion IVA:%c",*c.iva);
printf("\n Tipo de servicio:%d",*c.tiposerv);
printf("\n Monto a Cobrar:%f",*c.monto);
printf("\n");
printf("\n");
}
当我尝试显示结构时,指针没有显示我放置的值。
var TutorialSchema = new mongoose.Schema({
number: { type: String, required: true }
});
var CourseSchema = new mongoose.Schema({
name: { type: String, required: true },
code: { type: String, required: true, unique: true },
tutorials: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Tutorial' }]
});
答案 0 :(得分:1)
您正在将指向局部变量的指针分配给结构的字段。例如,®->tiposerv = &serv;
使字段tiposerv
指向serv
,这是函数中的局部变量。
当函数返回main
时,这些局部变量将被销毁。这就是为什么你没有得到他们的价值观。
一种可能的解决方案是使用malloc
动态分配指针字段。例如:
reg.tiposerv = malloc(sizeof(int));
*(reg.tiposerv) = serv;
答案 1 :(得分:1)
首先,®->iva = &letra;
,®->tiposerv = &serv;
和®->monto= &mon;
会发出编译错误,因为->
运算符在&
运算符和reg
之前进行了评估不是指针。
您应该只写(®)->iva
或更多reg.iva
。
然后,停止分配指向非静态局部变量的指针。它们将在退出范围时消失(在这种情况下退出函数cargarUno()
)并在此之后取消引用指针将调用未定义的行为。
一种解决方法是动态分配一些内存,如下所示:
char *letra = malloc(sizeof(char));
int *serv = malloc(sizeof(int));
float *mon = malloc(sizeof(float));
/* check if the allocations are successful here */
/* ... */
scanf("%c",letra);
reg.iva = letra;
/* correct lefthand operand of = as descrived above
* and remove & on the left of serv and mon like this */
如果你只分配指向单个数据的指针而你不会处理数组,我不认为使用这样的指针是好的。为什么不直接像这样直接存储数据:
typedef struct{
int numCliente;
tCadena nombre;
char iva;
int tiposerv;
float monto;
}tCliente;
/* ... */
scanf("%c",®.iva);
/* ... */
scanf("%d",®.tiposerv);
/* ... */
scanf("%f",®.monto);
答案 2 :(得分:0)
您没有为tCliente reg;
分配内存空间。
在为结构中的元素赋值之前,应先分配mem空间。
我修改了你的函数cargarUno()
,如下所示:
void cargarUno(tCliente *reg, int numC){
//tCliente reg;
...
reg->numCliente=numC;
...
leeCad(reg->nombre,20);
...
reg->iva = &letra;
...
reg->tiposerv = &serv;
...
reg->monto= &mon;
//return reg;
}
尝试为tCliente * reg分配内存空间,
int i=X; // assign the int you desire
tCliente *reg=malloc(sizeof(tCliente));
cargarUno(reg,i);