I am learning c in school , and having a little confusion on how to use type casting. here is my code.
I am trying to figure out what type casting is and how it works.
I initialized a pointer(ptr3) that points the adress of k, then initialized ptr4 and assign ptr3 that is converted into int*.
but this does not seem like working, since it gives random values every time.
Why is it?
I appreciate any feedback ! thank you so much.
#include <stdio.h>
int main() {
char k = 10;
char* ptr3 = &k;
int* ptr4 = (int*) ptr3;
printf("*ptr3 = %d *ptr4 = %d\n", *ptr3, *ptr4);
return 0;
}
output is
*ptr3 = 10 *ptr4 = 1669824522
You have two undefined behaviour in one line.
int *
pointer you read outside the k
object which is illegal.k
had enough size (for example is a char array), using the data as another type violates the strict aliasing rules - which is UB as wellGenerally speaking, do not typecast pointers unless you really know what you are doing. If you want to convert byte array to integer use memcpy
functionh.