How do I allocate 2D array of char array contiguously in memory and write to file in single call

154 views Asked by At

Here I come with my new C question, I have an array of char arrays and I want to reserve memory contiguously in memory to helps write into file with a single call.

ok, that's what I have:

#define PACKET_SIZE 40960
#define BUFFER_SIZE 3950
#define N_BUFFERS 4

typedef struct buffer{
  int lock;
  char (*rxbuf)[BUFFER_SIZE][PACKET_SIZE];
}buffer;

/* Buffer list */
buffer bufferlist[N_BUFFER];

[...]

/* I use this to init structs */
void initializeData() {
  for (int i = 0; i < N_BUFFER; i++) {
    bufferlist[i].lock = 0;
    bufferlist[i].rxbuf = malloc(sizeof(???)); /* ??? <- I don't know what to put here */
  }
}

/* After I insert data */
for (int ibuffer = 0; ibuffer < N_BUFFER; ibuffer++) {
  for (int idata = 0; idata < BUFFER_SIZE; idata++) {
    /* Here I want to pass char array[PACKET_SIZE] */
    int bytes_received = insertData(bufferlist[ibuffer].rxbuf[idata], sizeof(bufferlist[ibuffer].rxbuf[idata]));
    [...]
  }
}

[...]

/* Then write with this */
fwrite(bufferlist[i].rxbuf, sizeof(????), 1, outfile);

Please can you help me with this code?

Thanks in advance

3

There are 3 answers

1
Rohan On BEST ANSWER

Change your definition of char array in structure

char (*rxbuf)[BUFFER_SIZE][PACKET_SIZE];

to

char rxbuf[BUFFER_SIZE][PACKET_SIZE];

With this you already create char array and reserve memory, so no need to malloc().

You can do fwrite() as

fwrite(bufferlist[i].rxbuf, sizeof(bufferlist[i].rxbuf), 1, outfile);
3
this On

char (*rxbuf)[BUFFER_SIZE][PACKET_SIZE]; is only a single pointer to an 2D array of sizes BUFFER_SIZE and PACKET_SIZE.

If you want contiguous memory you can either change it to an 2D array

char rxbuf[BUFFER_SIZE][PACKET_SIZE];

or to a pointer to an array

char (*rxbuff)[BUFFER_SIZE] ;
rxbuff = malloc( sizeof( char ) * BUFFER_SIZE * PACKET_SIZE ) ;

In both ways the array is accessed in the same way rxbuff[0][0] = 'a' ;

0
alk On

Use

bufferlist[i].rxbuf = malloc(sizeof(*bufferlist[i].rxbuf)); 

That means: Allocate to bufferlist[i].rxbuf as much memory as needed by the variable bufferlist[i].rxbuf is pointing to.

Following this, the call to fwrite() would be:

fwrite(bufferlist[i].rxbuf, sizeof(*bufferlist[i].rxbuf), 1, outfile);