Little 'byte' of confusion

This is a discussion on Little 'byte' of confusion within the C++ Programming forums, part of the General Programming Boards category; When we say… Code: &(charArray[index * sizeof(int)]); …to retrieve the address to an integer value that stored inside a byte ...

  1. #1
    Registered User
    Join Date
    Jan 2004
    Posts
    22

    Little 'byte' of confusion

    When we say…

    Code:
    &(charArray[index * sizeof(int)]);
    …to retrieve the address to an integer value that stored
    inside a byte array, how actually it gets pointed to that
    value? Isn’t we are only getting the address of a single byte?

    As an example:
    if index is 5, doesn’t what we get only the address of
    the 5x4=20th byte of the byte array? Please someone explain…
    Thanks for reading. Have a really smooth day.
    - Kasun

  2. #2
    Registered User
    Join Date
    Feb 2004
    Posts
    46
    Isn’t we are only getting the address of a single byte?
    Yes. A pointer always points to a single byte since it can only hold a single address. However, the type of the pointer specifies how much memory after the initial address is part of the pointed to value and C++ makes sure that the correct type sizes are used.
    Code:
    #include <iostream>
    #include <cstdlib>
    
    using namespace std;
    
    int main()
    {
        unsigned char ca[2 * sizeof(int)];
        int ia[2] = {98, 97};
    
        memcpy(ca, ia, 2 * sizeof(int));
        int *p0 = (int*)&ca[1 * sizeof(int)];
        unsigned char *p1 = &ca[1 * sizeof(int)];
        cout<<"Sizeof *p0 "<< sizeof *p0 <<' '<< *p0 <<endl;
        cout<<"Sizeof *p1 "<< sizeof *p1 <<' '<< *p1 <<endl;
    }

  3. #3
    Registered User
    Join Date
    Jan 2004
    Posts
    22
    Oh.. yes. I see my mistake.
    - Thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. brace-enclosed error
    By jdc18 in forum C++ Programming
    Replies: 53
    Last Post: 05-03-2007, 05:49 PM
  2. About aes
    By gumit in forum C Programming
    Replies: 13
    Last Post: 10-24-2006, 03:42 PM
  3. Need some help regarding data structures
    By Afrinux in forum C Programming
    Replies: 15
    Last Post: 01-28-2006, 04:19 AM
  4. error: identifier "byte" is undefined.
    By Hulag in forum C++ Programming
    Replies: 4
    Last Post: 12-10-2003, 04:46 PM
  5. Byte confusion!!! HELP!
    By MrDoomMaster in forum C++ Programming
    Replies: 10
    Last Post: 11-12-2003, 03:54 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21