I'm a new user to C programming. I've tried researching this online, but couldn't find an answer... how to I access a portion of an array in C? For example,
int Data[4]
int Input[32]
What's the syntax for doing: D开发者_JAVA百科ata = Input[12:15] such that
Data[0] = Input[12]
Data[1] = Input[13]
Data[2] = Input[14]
Data[3] = Input[15]
In reality I'm trying to fill a portion of an array using a TCP socket:
recv(MySocket, YRaw[indx:indx+1024], sizeChunk, 0)
where I want the received data to be placed in YRaw array from array index 'indx' to 'indx+1024'.
Thanks in advance, gkk
For copying things from one array to another, you could use memcpy
:
#include "string.h"
memcpy(&input[12], &data[0], 4*sizeof(int)); /* source, destination, number of bytes to copy */
In the case of recv, you do the same thing - you pass in the pointer to the start and the number of bytes:
recv(sock, &YRaw[indx], sizeChunk*sizeof(int), 0); /* sizeChunk is hopefully 1024 */
Edit: I forgot sizeof from the second example so I added it.
could use memcpy
You could use pointer-arithmetics:
recv(MySocket, YRaw + indx, sizeof(int) * 1024, 0);
In this case, recv will place the first int at YRaw[indx], the second at YRaw[indx + 1], and so on.
In this example I assumed that you'd like to read integers from the socket.
Also, don't forget to check the return value.
精彩评论