Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

c - Why do I get weird results when reading an array of integers from a TCP socket?

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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_LEN or just sizeof (originalArray) instead.

Write:

#define ARRAY_LEN 4
long originalArray[ARRAY_LEN] = { 1, 2, 3, 4 };
write(clientSocketFD, originalArray, sizeof (originalArray));

Read:

#define ARRAY_LEN 4
long targetArray[ARRAY_LEN];
read(socketFD, targetArray, sizeof (targetArray));

If you are passing the array as a pointer, then sizeof cannot 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 with sizeof (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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...