As was suggested in an answer to my last question (How do I send an array of integers over TCP in C?), I tried to send an array of long int, however I may be doing something to break the solution…
#define ARRAY_LEN 4 /* I'm using long because the numbers are very large, * but in this example they're small to save space. */ long originalArray[ARRAY_LEN] = { 1, 2, 3, 4 }; myObject.SetMyArray(originalArray); // NOTE: The following is in a different function. long *myArrayFromFunction = myObject.GetMyArray(); write(clientSocketFD, myArrayFromFunction, sizeof(myArrayFromFunction) * ARRAY_LEN);
Is converting to a pointer then passing incorrect?
When reading on the client side, instead of getting the numbers I sent (1, 2, 3, 4), I get long numbers such as 140088443806649…
#define ARRAY_LEN 4 long targetArray[ARRAY_LEN]; read(socketFD, targetArray, sizeof(targetArray) * ARRAY_LEN);
So, assuming that I need to read into a pointer, I tried this…
#define ARRAY_LEN 4 long *targetArray; read(socketFD, targetArray, sizeof(targetArray) * ARRAY_LEN);
But this didn’t work either (the read function returned -1).
The extra pointer is unnecessary. The array (which basically is a pointer) can be passed directly. You are incorrectly using the size of the pointer instead of the size of the data type (long); use
sizeof (long) * ARRAY_LENor justsizeof (originalArray)instead.Write:
Read:
If you are passing the array as a pointer, then
sizeofcannot be used to get the total size of the array. In that case, the size must be passed along with the pointer and the size constructed withsizeof (long) * ARRAY_LEN.Be careful using a type such as long since it is not always the same size on different platforms (i.e. 32-bit versus 64-bit); favor sized types like int32_t instead. Also, you can run into issues with endianess as well. Consider byte-swapping the values with htonl before writing.