【问题标题】:Use void pointer to store float numbers into array使用 void 指针将浮点数存储到数组中
【发布时间】:2017-11-13 20:43:28
【问题描述】:

我是指针新手,这可能是一个愚蠢的问题。 无法使用 void 指针将浮点数存储到浮点数组中。下面是代码和输出:

代码:

int main()
{
int size=5;
float f_array[size];
populate(f_array, size);
// printing array below
}
void populate(void *p, int size)
{
    int i;
    for(i=0; i<size; i++)
    {
        scanf("%f", (((float *)p)+i));
    }
}

输出:

//输入五个浮点数存入数组

1.2 // 无法输入其他数字并给出以下输出

a[0] = 1
a[1] = garbage value
a[2] = garbage value
a[3] = garbage value
a[4] = 0

【问题讨论】:

  • 如果你在 main 之前定义 void populate(void *p, int size) 它可以正常工作,否则编译器可以为你的所有参数假定 int:如果是 64 位编译器,你就完蛋了。
  • 您是否启用了警告?你应该。
  • minimal reproducible example 请。我们看不到您如何打印您的价值观。我的水晶球告诉我你正在使用%d 格式
  • 我无法重现您的问题。也许您没有包含的打印功能有问题?
  • 代码没有任何输出代码。 “a[0] = 1 a[1] = 垃圾值...”的来源不可重新查看。

标签: c pointers void-pointers


【解决方案1】:
#include <stdio.h>
#define SIZE 5
void populate(void *p, int size)
{
    int i;
    float *array = (float*)p;
    for (i = 0; i < size; i++)
    {
        scanf("%f", &array[i]);
    }
}

int main()
{

    int i;
    float f_array[SIZE];
    populate(f_array, SIZE);
    //print array
}

【讨论】:

  • 行scanf("%f", &array[i]); - 需要使用指针而不是数组
  • 浮点 array = (float)p;这是转换为您的指针,数组也是指针......
猜你喜欢
  • 1970-01-01
  • 2016-01-22
  • 1970-01-01
  • 2018-05-02
  • 1970-01-01
  • 2019-02-03
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
相关资源
最近更新 更多