Pointers indicating an invalid location

#include <stdio.h>

int main(void)
{ 
   int x = 1000;
   char *ptr = &x;
   printf("%d\n",*ptr);
   return 0;
 }

Output: -24 /*In gcc 4.4.3 in Ubuntu 10.04 OS*/ At warning: initialization from incompatible pointer type

What I think, if the base type of the pointer was of type int, it would extract 4 bytes from the location that it pointed to. Then O / P would be 1000. But when I changed the base type to char then it will extract 1 byte from the location indicating when I am casting it. But the answer is -24. Again, when I changed the program as shown below

#include <stdio.h>

    int main(void)
    { 
       int x = 1000;
       float *ptr = &x;
       printf("%f\n",*ptr);
       return 0;
     }

The output becomes 0.000000 with the same warning. When I cancel the pointer, it will extract 4 bytes from the location that it points to. But like O / P - 0.000000. I'm a little confused. Perhaps the plz guys explain this .I is new in C programming, so any mistake in asking the question, plz forgive me. Thanx

+3
3

, 1000 . int ( varidac) integer.

, , -24.

, , 8- .

, , 4 8 .

, , 2s- , , .

, ?


float float char, (heh!), , , float int, .

, float*, float ( , 2s-) double ( varidac ), ( float int, double, , , int!). .

, , ​​ IEEE .

, :

.

,

- .

, .

+3

1000 0x3E8. int 32- little-endian, x :

+------+------+------+------+
| 0xE8 | 0x03 | 0x00 | 0x00 |
+------+------+------+------+
    ^
    |      ---increasing addresses--->
   &x

:

8- char, &x char *ptr, , 0xE8, char.

char , 2 , 0xE8 -24.

:

32- 32- float, &x float *ptr, , 0x000003E8, float.

float IEEE 754, (0 , ), 8 (0 , - ), 23 "" "" (0x3E8 1000). 1000 * 2 -149 1,4013 * 10 -42 - , %g %f printf.

+1

The core of your problem is that you tried to print char ( *ptr) as an integer ( %d).

Since you pointed the integer to printfwith %d, it will display 4 bytes from the stack to display.

However, since you transferred charin printf, you transferred only 1 byte. The remaining 3 bytes that are retrieved printfwill be random stack data and can be any.

As a result, you get -24 or some other inconsistent value.

-1
source

Source: https://habr.com/ru/post/1771024/


All Articles