2

In the following code:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{

    float *a; 
    printf("%x\n",&a);
    a = malloc(100*sizeof(float));
    printf("%x\n",a);
    *a=5;
    printf("%x\n",*a);
}

I expect to see "5" in the final output, but all I see is zero. How can I modify those memory space?

alk
  • 69,737
  • 10
  • 105
  • 255
C K
  • 344
  • 2
  • 13

2 Answers2

4

I expect to see "5" in the final output, but all I see is zero. How can I modify those memory space?

Use "%f" (or "%g" etc appropriate identifier) to print the value. (Or use explicit casting to unsigned int and print sizeof(double) * CHAR_BIT bits)

Printing a double argument with "%u" printf format specifier leads to undefined behavior. Related post: Understanding implicit conversions for printf

Can't modify values at addresses allocated by malloc()

You should be able to modify the contents on conforming implementation if a is not NULL. There is problem in presenting the data.

Community
  • 1
  • 1
Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
1

I believe this is the working answer to your question. It seems to be about printf() format specifiers and entering float value as float, not as integer:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
float *a; 
printf("%p\n",(void*)a);
a = malloc(100*sizeof(float));
printf("%p\n",(void*)a);
if(a != NULL) *a=5.0;
printf("%f\n",*a);
}

The terminal output then looks like this:

> ./a.out
0x0
0x1031009a0
5.000000
>
user3078414
  • 1,942
  • 2
  • 16
  • 24
  • 1
    Don't print uninitialized pointer. Cast pointer to `void *` before printing. – Mohit Jain Apr 20 '16 at 09:20
  • 1
    Thanks for this suggestion @Mohit Jain - I improved my reply by including it. Although "printfing" uninitialized pointers provenly works with my BSD UNIX, one always has to be extra cautious with _uninitialized pointers_ in portable code. (-: – user3078414 Apr 20 '16 at 09:27