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
-
Have you read stackoverflow.com/questions/18814773/… and stackoverflow.com/questions/3376740/… ? Yours is possibly a duplicate question.ericbn– ericbn2013年12月19日 12:34:06 +00:00Commented Dec 19, 2013 at 12:34
-
@ericbn Thanks but neither was helpful. First needs loop and second is C++hiroru– hiroru2013年12月23日 17:53:09 +00:00Commented Dec 23, 2013 at 17:53
3 Answers 3
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);
1 Comment
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);
Comments
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' ;
Explore related questions
See similar questions with these tags.