Reading data from buffer using pointers

This is a discussion on Reading data from buffer using pointers within the C Programming forums, part of the General Programming Boards category; I am having a brainfart atm. I have a character array defined as buffer[1024]. When my code is executed, it ...

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

    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,185
    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,211
    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
    398
    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 06: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, 05:40 AM
  3. Reading data from a text file
    By Dark_Phoenix in forum C++ Programming
    Replies: 8
    Last Post: 06-30-2008, 03:30 PM
  4. Please Help Reading Data From A File
    By NickHolmes in forum C Programming
    Replies: 5
    Last Post: 05-30-2005, 12:24 AM
  5. Reading data from buffer
    By timmer in forum C++ Programming
    Replies: 2
    Last Post: 04-25-2005, 08:03 AM

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