0

I am currently writing a terminal based hex editor. and I have a few question regarding memory allocation.

To track changes the user has made I write them to an array of arrays like so, the [i][0] is the absolute offset of the change from the beginning of the file and [i][1] is the change itself:

unsigned long long writebuffer[10000][2];

but I have 2 problems with this. the first array (writebuffer[i][0]) NEEDS to be the sizeof unsigned long long but the second one ([i][1]) can be as small as sizeof unsigned char. Is it possible to do something like this??

also can I dynamically allocate the first index of writebuffer so I wouldn't initialize it like above but more like:

unsigned long long **writebuffer;

and then change the first index with malloc() and realloc(); while the second index would be 2 but have the size of a unsigned char.

2
  • 2
    Use a struct of one unsigned long long and one unsigned char? Commented Jan 21, 2014 at 21:57
  • damn so easy. yes that works Commented Jan 21, 2014 at 21:58

2 Answers 2

1

Why not use a struct?

typedef struct {
    long long offset;
    int change; /* or unsigned short, or whatever you feel is right */
} t_change;

Be aware that the struct will likely get padded by the compiler to a different size if you choose to use unsigned char for the change element. What it gets padded to depends on your compiler, the compiler settings, and the target architecture.

Sign up to request clarification or add additional context in comments.

3 Comments

hmm why does unsigned char get padded? my changes are ALWAYS only 1 byte long. so it would be ideal to get them to always be the size of char.
@user3188237: The struct contains a long long offset. In most C implementations, long long objects are required to be aligned in memory, to addresses that are multiples of four bytes or more. If the size of the struct were just the size of a long long plus the size of an unsigned char, then it would be something like nine bytes. Then an array of the struct would have elements at offsets of 0, 9, 18, 27, 36,… bytes from the start of the array. This would force some of the offset members to be unaligned. That is not allowed. So the compiler pads the struct to make the multiples align.
I see. Another small question. If I want to realloc() a struct made from this what would I use? I want to do this before I add a change. writebuffer=realloc(writebuffer(++wrcount)*sizeof(???));
0

You may define an array of type void:

void **writebuffer;

and then allocate and use each element as you like, for example:

*writebuffer[0] = (char*)malloc(sizeof(char));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.