有人可以告诉我代码有什么问题吗?抱歉,如果我是新手,但很长一段时间以来我一直在努力解决这个问题。我正在尝试从用户那里获取输入,然后打印值。以下代码仅是示例。
我尝试运行代码,但出现运行时错误。有人可以帮忙吗?
#include <stdio.h>
#include <stdlib.h>
typedef struct poly
{
int kill;
float bill;
char katana[50];
} koly;
typedef koly* terma;
int main()
{
int count = 0;
terma ren;
ren = (terma)malloc(sizeof(koly));
ren = (terma)realloc(6*sizeof(koly));
printf("We can store now:\n\n");
while(++count<= 2)
{
scanf("%d",ren->kill);
scanf("%f",ren->bill);
scanf("%s",ren->katana);
}
while(++count<= 2)
{
printf("\n%d\n",ren->kill);
printf("\n%f\n",ren->bill);
printf("\n%s\n",ren->katana);
}
}
关于您的错误:
scanf("%d",ren->kill);
scanf("%f",ren->bill);
这些应该是指针,所以更正的版本是:
scanf("%d",&ren->kill);
scanf("%f",&ren->bill);
另外,realloc
期望2个参数与有所不同malloc
。第一个应该是您要重新分配的地址的指针,第二个应该是新的大小。所以:
ren = realloc(ren, 6 * sizeof(koly));
关于您的代码,我还有两件事要说。首先:不必强制转换malloc
C的返回值(并且不赞成)。另外,切勿scanf
与"%s"
格式说明符一起使用。这是非常不安全的,很容易导致崩溃甚至更糟。最好的方法是使用fgets
,因此scanf("%s",ren->katana);
将变为:
fgets(ren->katana, sizeof(ren->katana), stdin);
编辑:这是我的解释,为什么应避免强制转换malloc
/的返回值realloc
:
这不是真的因为错了。这是因为在C语言中这样做是一种不好的做法。由于将void*
类型自动转换为任何指针类型,因此类型转换是多余的,代码的可读性(IMO)较低,并且使更改更加困难。例如,考虑一下您的情况:
ren = (terma)malloc(sizeof(koly));
我个人将这样重写此行:
ren = malloc(sizeof(*ren));
这样可以轻松更改的类型ren
。如果ren
更改为其他数据类型(例如int*
或struct sockaddr_in*
或其他),它将自动运行。您无需更改演员表中的类型或中的类型sizeof()
。两者都将自动适用于新类型。对于数组,其工作原理相同:
int* myArr = malloc(42 * sizeof(*myArr));
如果我想myArr
保留一个42 float
s的数组,则更改很简单:
float* myArr = malloc(42 * sizeof(*myArr));
注意:在C ++中,必须进行类型转换,因为它不会自动转换void*
为其他指针类型,但是您确实应该在任何情况下都不要malloc
在C ++中使用et al new
(另外,这是一个C问题,而不是C ++)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句