Don't cast malloc
, and also check the return value of malloc
, if it
returns NULL
, you cannot access the memory otherwise it's undefined behaviour.
float *ptr = malloc(5 * sizeof *ptr);
if(ptr == NULL)
{
fprintf(stderr, "Not enough memory\n");
return; // or exit or whatever
}
Also note that dynamically allocating space is usually needed when the size is
not known at compile time, because the user inputs the size or it has to be
calculated. In your example you already know the size, malloc
is not needed.
float arr[5];
would be enough.
getchar();
returns a single character. The value of the character is
determined by the ASCII table. The value for '1'
is not the same as the
value 1, because '1'
is 49. You have to read all the characters forming a
number and then convert them to float
using functions like scanf
or strtof
.
Alternative 1: using scanf
.
// assuming you are using ptr = malloc(...)
for(size_t i = 0; i < 5; ++i)
{
while(scanf("%f", ptr + i) != 1)
{
// clear buffer
int c;
while((c = getchar()) != '\n' && c!= EOF));
if(c == EOF)
{
// cannot continue doing scanf
free(ptr);
return; // or exit
}
printf("Please re-enter the number:\n");
}
}
Alternative 2: using fgets
char line[50];
for(size_t i = 0; i < 5; ++i)
{
while(1) // continue reading if value is not a float
{
if(fgets(line, sizeof line, stdin) == NULL)
{
// cannot continue reading
free(ptr);
return; // or exit
}
char *end;
float val = strtof(line, &end);
if(*end == '\n' || *end == '\0')
{
ptr[i] = val;
break; // exit while(1) loop, continue reading next value
} else
printf("Please re-enter the number:\n");
}
}
Also at the end do not forget to free the memory with free(ptr);
.