简体   繁体   中英

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. 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. First, use a fixed width type for array else you might get the wrong size integer.

#include <stdint.h>

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

Then read straight from the file into the array, two 4 byte integers at time.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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