Sushmita Limkar
Sushmita Limkar

Reputation: 21

Use void pointer to store float numbers into array

I'm new to pointers and this may be a silly question. Not able to store float numbers into float array using void pointer. Below is the code and the output:

Code:

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));
    }
}

Output:

//Entering five float numbers to be stored in array

1.2 // not able to enter other numbers and gives the below output

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

Upvotes: 1

Views: 1117

Answers (1)

Elad Hazan
Elad Hazan

Reputation: 331

#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
}

Upvotes: 1

Related Questions