Ajay Ramesh Ajay Ramesh - 1 month ago 10
C Question

How to write exact 1MB array in C?

I want to initialize an array of size 1MB. So my goal is finally write that 1MB to a file.
I am curious every time i use this formula it is giving less than 1mb.

int len = (1048576)/sizeof(int);
data = (int *) malloc(len);


What is correct way ?
Thank you




Edit - As per the comments I have changed the code .

#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <string.h>

int main(int argc, char *argv[]) {
int *data;
int bytes = (1024*1024);
data = (int *) malloc(bytes);
for(int i=0;i<bytes;i++){
data[i] = (int)rand();
printf("%d",data[i]);
}
return 0;

}


After compiling it and I tried dumping the data like below

mpicc -o a mpiFileSize.c

./a > dump.dat


Now I see the file size of dump.dat. Why its 2.5MB ?
File Size in Mac

Answer

Try this

#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <string.h>

int main(int argc, char *argv[]) {
char *data;
int bytes = (1024*1024);
data = (char *) malloc(bytes);
for(int i=0;i<bytes;i++){
 data[i] = (char) rand();
 printf("%c",data[i]);
}
return 0;

}

You shoul use character instead of integer.

Comments