Is it possible to store a value directly to a double or float pointer?
int *ptr1;
double *ptr2;
*ptr1 = 12;
*ptr2 = 10.50; //is this really not allowed in C?
printf("%d\n", *ptr1);
printf("%f\n", *ptr2); //this does not display 10.50
Yes it is really not allowed in C to assign values to memory referenced by incorrectly/not initialised pointers.
You need to use malloc()
(or siblings from the allocation family) or the address operator &
.
It is however allowed to do this part of your code
*ptr1 = 12;
*ptr2 = 10.50;
AFTER you correctly initialised the pointers.
The fact that you probably can compile and run the shown code and even get the "expected" result, does not contradict this. It is called undefined behaviour and it is worse than having a program not compile or not generate useful results. If you are lucky you get a segmentation fault for this, but not getting one still does not prove anything.
You have to allocate memory for the dynamically allocated variables. (int
and double
pointers in this case). Your current code will likely result in segmentation fault. (as it is undefined behavior to access the address of an uninitialized pointer variable)
#include <stdio.h>
#include <stdlib.h> // needed for malloc()
int main(int argc, char const *argv[])
{
int *ptr1 = (int*) malloc(sizeof *ptr1);
double *ptr2 = (double*) malloc(sizeof *ptr2);
*ptr1 = 12;
*ptr2 = 10.50; //allowed in C
printf("%d\n", *ptr1);
printf("%f\n", *ptr2); //this does display 10.50
free(ptr2);
free(ptr1);
return 0;
}
Output:
12
10.500000
You have 2 ways to do this:
int i1;
double d2;
int *ptr1 = &i1;
double *ptr2 = &d2;
*ptr1 = 12;
*ptr2 = 10.50; // now it is ok, because pointers points to valid memory
printf("%d\n", *ptr1);
printf("%f\n", *ptr2); // this displays 10.50
int *ptr1 = malloc(sizeof(int));
double *ptr2 = malloc(sizeof(double));
*ptr1 = 12;
*ptr2 = 10.50; // now it is ok, because pointers points to valid memory
printf("%d\n", *ptr1);
printf("%f\n", *ptr2); // this displays 10.50
free(ptr1);
free(ptr2); // NOW YOU HAVE TO FREE ALLOCATED MEMORY BY YOURSELF