我已经使用malloc创建了一个动态 vector ,如果我使用整个数字创建它,就没有问题,但是一旦我像代码中那样使用double,我得到了错误的答案,而不是打印35和88.5,我得到了0和0,有谁知道为什么吗?
#include <stdio.h>
#include <stdlib.h>
int main()
{
double * dd;
dd = malloc(2*sizeof(double*));
dd[0] = 35;
dd[1] = 88.5;
printf(" %d ",dd[0]);
printf(" %d ",dd[1]);
return 0;
}
最佳答案
您的代码有两个问题
dd = malloc(2*sizeof(double*));
这是为 2 个 double
指针分配空间,您应该使用
sizeof(double)
或者更好的是这样做:
dd = malloc(2 * sizeof *dd);
if(dd == NULL)
{
// error handling
// do not continue
}
第二个问题是 %d
是 int
的转换说明符,你是
传递 double ,这会产生未定义的行为。您必须使用%f
printf(" %f\n", dd[0]);
printf(" %f\n", dd[1]);
man 3 printf
Conversion specifiers
d, i: The
int
argument is converted to signed decimal notation. The precision, if any, gives the minimum number of digits that must appear; if the converted value requires fewer digits, it is padded on the left with zeros. The default precision is 1. When 0 is printed with an explicit precision 0, the output is empty....
f, F: The
double
argument is rounded and converted to decimal notation in the style[-]ddd.ddd
, where the number of digits after the decimal-point character is equal to the precision specification. If the precision is missing, it is taken as 6; if the precision is explicitly zero, no decimal-point character appears. If a decimal point appears, at least one digit appears before it.
并且不要忘记释放内存
free(dd);
所以你的程序应该是这样的:
#include <stdio.h>
#include <stdlib.h>
int main()
{
double * dd;
dd = malloc(2 * sizeof *dd);
if(dd == NULL)
{
fprintf(stderr, "Not enough memory\n");
return 1;
}
dd[0] = 35;
dd[1] = 88.5;
printf(" %f\n", dd[0]);
printf(" %f\n", dd[1]);
free(dd);
return 0;
}
关于c - Malloc 和双重发行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49759849/