extracting value from array

This is a discussion on extracting value from array within the Windows Programming forums, part of the Platform Specific Boards category; I have an array like this char Data[10]; I am trying to extract a dword like this dwNumber=Data[2]; This dosen't ...

  1. #1
    ENF
    ENF is offline
    Registered User
    Join Date
    Oct 2003
    Posts
    12

    extracting value from array

    I have an array like this
    char Data[10];

    I am trying to extract a dword like this
    dwNumber=Data[2];
    This dosen't work
    I've also tried
    dwNumber=(DWORD)Data[2];
    still dosen't work I guese it is just getting one byte since Data is an array of chars. The only way I have been able to do it is like this
    memcpy(&dwNumber, (LPVOID)&Data[2], 4);
    This seams like overkill there must be a better way to take a dword value from an arraw of chars.

  2. #2
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,691
    You want to cast the address of Data[2] as a pointer to WORD then dereference it.
    Code:
    #include <windows.h>
    #include <iostream>
    using namespace std;
    
    int main()
    {
        WORD wData[5] = {1, 2, 3, 4, 5};
        char *bData = (char*)wData;
        int n = 0;
    
        for (; n < 5; n++)
        {
            WORD *pval = (WORD*)(bData + (n * 2));
            // or
            WORD val = *((WORD*)&bData[n * 2]);
    
            cout << *pval << ", " << val << endl;
        }//for
    
    	return 0;
    }//main
    gg

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. array of pointers/pointer arithmetic
    By tlpog in forum C Programming
    Replies: 18
    Last Post: 11-09-2008, 07:14 PM
  2. 1-D array
    By jack999 in forum C++ Programming
    Replies: 24
    Last Post: 05-12-2006, 08:01 PM
  3. 2d array question
    By gmanUK in forum C Programming
    Replies: 2
    Last Post: 04-21-2006, 01:20 PM
  4. extracting data from file putting it into an array..
    By Cat00 in forum C++ Programming
    Replies: 4
    Last Post: 03-30-2005, 02:48 PM
  5. Template Array Class
    By hpy_gilmore8 in forum C++ Programming
    Replies: 15
    Last Post: 04-12-2004, 12:15 AM

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