-1

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
Rob Perez
  • 9
  • 3

3 Answers3

2

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.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
  • Why is it a char pointer does not nid to be allocated in malloc? My compiler accepts char pointer with or iwthout mallod. – Rob Perez Aug 31 '19 at 23:46
  • A char pointer does not occur in your code. I can guess a few scnearious in which you new question might be applicable, but it would need the space of a new question to discuss them. Please ask a new question on allocation/non-allocation of char pointers, with a MCVE to demonstrate the cases you are referring to. Is anything still unclear about this question as you have asked it? – Yunnosch Sep 01 '19 at 05:22
0

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
Robur_131
  • 374
  • 5
  • 15
0

You have 2 ways to do this:

  • Statically:
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

  • Dynamically:
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
marcos assis
  • 388
  • 2
  • 14