如何寻址(一维)数组的一部分?

发布于 2024-09-16 07:43:00 字数 442 浏览 4 评论 0原文

我是 C 编程的新用户。我尝试过在线研究这个问题,但找不到答案...如何访问 C 中数组的一部分?例如,

int Data[4]
int Input[32]

执行的语法是什么: Data = Input[12:15] 这样

Data[0] = Input[12]
Data[1] = Input[13]
Data[2] = Input[14]
Data[3] = Input[15]

实际上我正在尝试使用 TCP 套接字填充数组的一部分:

recv(MySocket, YRaw[indx:indx+1024], sizeChunk, 0)

我希望将接收到的数据放置在 YRaw 数组中数组索引“indx”到“indx+1024”。

预先感谢,gkk

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: Data = 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

み青杉依旧 2024-09-23 07:43:00

要将内容从一个数组复制到另一个数组,您可以使用memcpy:

#include "string.h"

memcpy(&input[12], &data[0], 4*sizeof(int)); /* source, destination, number of bytes to copy */

在recv的情况下,您执行相同的操作 - 传入指向开头的指针和字节数:

recv(sock, &YRaw[indx], sizeChunk*sizeof(int), 0); /* sizeChunk is hopefully 1024 */

编辑: 我忘记了第二个示例中的 sizeof,所以我添加了它。

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.

凉城 2024-09-23 07:43:00

可以使用memcpy

could use memcpy

荒芜了季节 2024-09-23 07:43:00

您可以使用指针算术:

recv(MySocket, YRaw + indx, sizeof(int) * 1024, 0);

在这种情况下,recv 会将第一个 int 放置在 YRaw[indx] 处,第二个 int 放置在 YRaw[indx + 1] 处,依此类推。

在此示例中,我假设您想从套接字读取整数。

另外,不要忘记检查返回值。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文