简体   繁体   English

为2D数组指定指针值

[英]Assigning a value of pointer to a 2D array

I have this following piece of code which is working fine: 我有以下这段代码正常工作:

int array[16][2] = {{0}};

void *buffer_ptr = NULL;

get_buffer(&buffer_ptr); // This is a function which gives me the address of 
buffer ptr

file_read(handle, size, buffer_ptr); // This function reads and stores data into buffer_ptr

Now I want to copy this read value into buffer_ptr into array. 现在我想将这个读取值复制到buffer_ptr中。 I am doing this currently which works: 我这样做目前有效:

for (i = 0; i < 16; i++)
{
    array[i][0] = *((int *)buffer_ptr+(2*i));
    array[i][1] = *((int *)buffer_ptr+(2*i)+1);
} 

But I am sure there is a better way to do this. 但我相信有更好的方法可以做到这一点。

Thanks. 谢谢。

But I am sure there is a better way to do this. 但我相信有更好的方法可以做到这一点。

Yes, read directly into the array. 是的,直接读入数组。 There's no need for the intermediate buffer. 不需要中间缓冲区。

I'm going to guess your file is a bunch of 4 byte integers and you want them two at a time. 我猜你的文件是一堆4字节的整数,你希望它们一次两个。 First, use a fixed width type for array else you might get the wrong size integer. 首先,对array使用固定宽度类型,否则可能会得到错误的大小整数。

#include <stdint.h>

int32_t array[16][2] = {{0}};

Then read straight from the file into the array, two 4 byte integers at time. 然后直接从文件读入数组,两个4字节整数。

FILE *fp = fopen(file, "rb");
if( fp == NULL ) {
    fprintf(stderr, "Could not open '%s' for reading: %s\n", file, strerror(errno));
    exit(1);
}

for (int i = 0; i < 16; i++)
{
    fread(array[i], 4, 2, fp);
}

I believe you can even cut that down to a single read. 我相信你甚至可以把它减少到一次阅读。

fread(array, 4, 32, fp);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM