0

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.

3
  • 1
    What else would you expect to be shown, when you seem to know that char and int have different sizes? Do you know how numbers are stored in memory? Commented Jan 7, 2023 at 19:45
  • int uses 4 bytes, char uses 1 byte. So you're seeing each of the 4 bytes in the numbers when you use p[i]. Commented Jan 7, 2023 at 19:47
  • 1
    @Badie Sakka, Try int tab[]={0x04030201, 0x08070605, 0x0C0B0A09, 0x100F0E0D, 0x14131211};. What does your code print? Commented Jan 7, 2023 at 20:25

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.