title: Casting a pointer - What is the difference at runtime?
body: <p>Consider the following small example code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  int main()
  {
      int *i;
      char *c1, *c2;
  
      i = malloc(4);
  
      *i = 65535;
  
      c1 = i;
      c2 = (char *)i;
  
      printf("%p %p %p\n", i, c1, c2);
      printf("%d %d", *c1, *c2);
  
      free(i);
  
      return 0;
  }
  </code></pre>
  
  <p>In the example, I allocate memory to store an integer, which is pointed by <code>i</code>. Then, I store the value 65535 (1111 1111 1111 1111) in <code>*i</code>. The next thing I do is make two <strong>char*</strong> pointers also point to the integer. I do it two times, but in two different ways: <code>c1 = i;</code> and <code>c2 = (char *)i;</code>. Finally, I print all pointers and all values in the screen. The three pointers are pointing to the same address, and the two values <code>*c1</code> and <code>*c2</code> are correct <strong>(-1)</strong>.</p>
  
  <p>However, the compiler generates a warning in this line: <code>c1 = i;</code>. The warning is generated because I did not use the <code>(char *)</code> cast to do the assignment.</p>
  
  <p>What I would like to ask is <strong>why</strong> the compiler generates this warning, since I do not see <strong>any difference</strong> in using <code>c1 = i</code>; or <code>c2 = (char *)i;</code>. In both cases, the result is the same address with the same size in bytes. And this is valid for all casts, even if it is a <code>(int *)</code> cast, <code>(float *)</code> cast, <code>(short *)</code> cast, etc. All of them generate the same value, but the compiler will only accept it without a warning if the cast being used is of the pointer's type.</p>
  
  <p>I really would like to know why the compiler asks for that cast, even if the result is always the same.</p>