cpointerstypescastingtypecasting-operator

Type casting from char* to int*


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

Solution

  • You have two undefined behaviour in one line.

    1. When you dereference int * pointer you read outside the k object which is illegal.
    2. Even if the 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 well

    Generally 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.