c - Malloc 和双重发行

标签 c double malloc

我已经使用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
}

第二个问题是 %dint 的转换说明符,你是 传递 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/

相关文章:

c - C 中的任何系统调用都可以在非根用户模式下更改 HP-UX 中文件的权限吗?

c++ - 在 C++ 中检查 double (或 float )是否为 NaN

c - 为什么 malloc 在没有转换的情况下不起作用?

c - 字符串转换为整数而不是 double

python - 如何使代码同时接受 int 和 float 类型值作为 double 类型? - Python

c - 将数字从文件传递到结构中

c - 在 C 中分配二维数组

c - 我应该使用什么数据结构来计算超过 50 位数字的阶乘?

C 如何检查数组是否已满?

c - 为什么这段代码是正确的?