1

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
6
  • 1
    it works properly if you define void populate(void *p, int size) before the main, else compiler could assume int for all your parameters: if 64 bit compiler you're toast. Commented Nov 13, 2017 at 20:50
  • have you enabled the warnings? you should. Commented Nov 13, 2017 at 20:51
  • 2
    minimal reproducible example please. We don't see how you're printing your values. My crystal ball tells me you're using %d format Commented Nov 13, 2017 at 20:53
  • 1
    I am unable to reproduce your problem. Perhaps there is a problem with the print function that you did not include? Commented Nov 13, 2017 at 20:57
  • Code does not have any output code. Source of "a[0] = 1 a[1] = garbage value ..." is not re-viewable. Commented Nov 13, 2017 at 22:31

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

at line scanf("%f", &array[i]); - it is required to use pointers instead of array
float array = (float)p; this is casting to your pointer, and arrays are pointers as well...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.