【发布时间】:2013-09-27 22:26:51
【问题描述】:
我正在尝试做一个简单的练习,我应该在哪里使用指针和 malloc 在结构中输入 2 个输入(monto 和 loc)。当我尝试打印数据时,它显示垃圾。我试图检查发生了什么,所以我在输入后打印数据并显示如下内容 -1414812757 -158839287345460020000000000000000000000.00
struct transaccion{
int loc;
float monto;
char nombre[50];
} cliente,*pcliente;
int cargadatos (struct transaccion*);
void mostrarlocalidad(struct transaccion*,int);
void mostrarestructura(struct transaccion*);
void main()
{
int tam=50,ll;
struct transaccion *pTrans;
pTrans=(struct transaccion*)malloc(sizeof(struct transaccion)*tam);
pTrans[0].monto=5;
if(pTrans==NULL){
puts("Falta memoria");
exit(3);
}
ll=cargadatos(pTrans);
mostrarlocalidad(pTrans,ll);
free(pTrans);
system("pause");
}
int cargadatos (struct transaccion *pTrans)
{
int i=0;
while (pTrans[i].loc!=0){
puts ("ingrese numero de localidad");
scanf("%d", &pTrans[i].loc); fflush (stdin);
puts ("ingrese monto");
scanf("%.2f",&pTrans[i].monto); fflush(stdin);
int j=0;
for (j=0; j<=i; j++) {
if (pTrans[j].loc==pTrans[i].loc){
pTrans[j].monto=pTrans[j].monto+pTrans[i].monto;
i--;
}
}
printf("%d %.2f \n",pTrans[i].loc,pTrans[i].monto);
i++;
}
return;
}
我已经尝试了好几个小时,但我无法弄清楚错误在哪里。
【问题讨论】:
-
malloc没有初始化分配的内存块! -
谁/什么建议使用
fflush(stdin)? -
(1)
void main()错误; (2)fflush(stdin)是未定义的行为; (3) 将i设置为0,每循环递减一次,然后检查j <= i是否为真,这只会在第一个循环中为真,然后你尝试打印pTrans[-1]; (4) 你没有#include任何标题; (5) 你称它为“C++”,但你使用的是malloc()和free(); (6) 等等等等等等,你从哪里弄来的这些奇怪的东西? -
@chux 这是微软特有的 hack 来吞下换行符(符合标准的解决方案是让 scan 调用本身吞下尾随空格)
-
附带问题:
ll=cargadatos(pTrans);,但cargadatos(pTrans)不返回值,只是一个return;。
标签: c