First ensure that your do while
block works as expected.
Concerning you question
As we know one dimensional array can be think as pointer to memory block. so
char *ar = recvbuf ;
char x1= *ar; //will get first byte (index 0)
char x2=*(ar+1); //will get second byte (index 1)
Also as array and pointer in our case can be used interchangeable We can access as indexed way too
char x1=ar[0];// the same as *ar
char x2=ar[1]; //= *(ar+1);
As you see char will move one byte, but in our case we want to move 4 bytes. so we will make our pointer to point to int.
int *intarr=(int *) recvbuf ; //recvbuf is address
now we can access and fetch ints using the same syntax
int x1=*intarr;
int x2= *(intarr+1); // *((int*)(ar+4))
//or
int x1=intarr[0];
And note that if inarr
point to for example to address 00004
, (inarr+1)
will point to
00004+ 4=00008th
address. Cause pointer arithmetic will know that next int address will be obtained using addr+sizeof(int)
.
Next issue. Bytes order can be different. see endianness
On that case we have to make conversion. either we will write our functions. or we can use
htonl ntohl
. Or see this manual conversion endiannes conversion on stackoverflow
Then coming to my code: uint32_t *endp=(uint32_t*)(recvbuf+iResult);
will point to end of our array. so we will increment our pointer until it be equal to endp; while(p<endp) ++p;
and simple we will use *
dereference operator to get that value. after ++p p
will point to next int block,and fetching uint32_t
from that address will be equal to *p
. And we will increment that until endp
Another option just to use index syntax. so we have to first calculate length of our array. How many ints we got in our array .this will be equal iResult/sizeof(uint32_t)
iResult our length in bytes
. After that we can access index using *(p+index)
or more nice way p[index]
...
uint32_t *p=(uint32_t*)recvbuf;
uint32_t *endp=(uint32_t*)(recvbuf+iResult);
//here is accessing
while(p<endp){
//ntohl(*p) if it was send from begin endian
uint32_t value=*p;p++;
}
//or
uint32_t *p=(uint32_t*)recvbuf;
size_t len=iResult/sizeof(uint32_t);
//
for(int i=0;i<len;i++){
uint32_t value= p[i]; //and again if there is endian problem solve it using ntonl htonl
}