Thread: Reading data from buffer using pointers

  1. #1
    Registered User carrotcake1029's Avatar
    Join Date
    Apr 2008
    Posts
    404

    Reading data from buffer using pointers

    I am having a brainfart atm. I have a character array defined as buffer[1024]. When my code is executed, it get filled up with various data. I know that starting at buffer[2] is an unsigned short. This obviously stretches from buffer[2] to buffer[3]. I am trying to assign it to a variable, but am stumped because I am not getting the right out put.

    Would this not be the way to do it?
    Code:
     var = (unsigned short)buffer[2];
    or something similar? I have been working on this project too long.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Maybe
    Code:
    unsigned short *temp = buffer[2];
    var = *temp;
    In other words, you'll need to dereference a pointer that points to the right spot.

  3. #3
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Shouldn't that be....

    Code:
    unsigned short *temp = (unsigned short *)&buffer[2];
    var = *temp;
    Edit: And btw, this doesn't take endianess into account.

  4. #4
    Registered User carrotcake1029's Avatar
    Join Date
    Apr 2008
    Posts
    404
    Thank you, that helped me. Helped to fix the logic in my brain. The endianess does need to be checked, but I can handle that, it is network traffic coming in.
    Code:
    					temp = (unsigned short *)&recvbuf[2];
    					port = *temp;
    					printf("Port Number: %d\n", ntohs(port));
    Last edited by carrotcake1029; 07-18-2008 at 05:50 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 7
    Last Post: 02-02-2009, 07:27 AM
  2. Does realloc save the previous buffer data?
    By Niara in forum C Programming
    Replies: 6
    Last Post: 07-23-2008, 04:40 AM
  3. Reading data from a text file
    By Dark_Phoenix in forum C++ Programming
    Replies: 8
    Last Post: 06-30-2008, 02:30 PM
  4. Please Help Reading Data From A File
    By NickHolmes in forum C Programming
    Replies: 5
    Last Post: 05-29-2005, 11:24 PM
  5. Reading data from buffer
    By timmer in forum C++ Programming
    Replies: 2
    Last Post: 04-25-2005, 07:03 AM