Home > Back-end >  Casting an int array into a char pointer in c
Casting an int array into a char pointer in c

Time:01-08

I ran through these few lines of code in C:

int tab[]={4,6,8,9,20};
char *p;     
p=(char*)tab

And the question was how to print the value of 20 using the pointer p.

So i used a for loop to see what's going on with p

    for(int i=0;i<20;i  ){
        printf("%d ",p[i]);
    }

and i got this output:

4 0 0 0 6 0 0 0 8 0 0 0 9 0 0 0 20 0 0 0

i want to understand the logic behind those zeros appearing.

CodePudding user response:

You are almost certainly using an architecture where int is 4 bytes, and a little-endian architecture where the "smallest" byte is stored first.

So the int value 4 is stored as:

 ---- ---- ---- ---- 
|  4 |  0 |  0 |  0 |
 ---- ---- ---- ---- 

The int value 20 gets stored as:

 ---- ---- ---- ---- 
| 20 |  0 |  0 |  0 |
 ---- ---- ---- ---- 

Your entire array in memory looks like:

 ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 
|  4 |  0 |  0 |  0 |  6 |  0 |  0 |  0 |  8 |  0 |  0 |  0 |  9 |  0 |  0 |  0 | 20 |  0 |  0 |  0 |
 ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- 

Now, when you iterate over those 20 bytes as characters (and thus one byte at a time) the results should no longer be surprising.

CodePudding user response:

On your machine, the sizeof an int is 4 bytes, and sizeof a char is by definition 1.

So with p, you're printing an int byte by byte.


"And the question was how to print the value of 20 using the pointer p."


As for that:

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

int main(void) 
{
     int tab[] = {4, 6, 8, 9, 20};
     char *p = 0;     
     
     /* The type that & returns is a 
     *  pointer type, in this case, a 
     *  pointer to the 4th element of 
     *  the array.
     */
     p = (char*) &tab[4];
     
     /* As %d expects an int, we cast 
     *  p to an int *, and then 
     *  dereference it. 
     */
     printf("%d\n", *(int *)p);
     return EXIT_SUCCESS;
}

Output:

20

Edit: The above code is endian-dependent.

  • Related