Tuesday 8 November 2011

How do you declare an array that will hold more than 64KB of data? in C programming

How do you declare an array that will hold more than 64KB of data?

The coward’s answer is, you can’t, portably. The ANSI/ISO C standard requires compilers to handle only
single objects as large as (32KB – 1) bytes long.
Why is 64KB magic? It’s the biggest number that needs more than 16 bits to represent it.
For some environments, to get an array that big, you just declare it. It works, no trouble. For others, you can’t
declare such an array, but you can allocate one off the heap, just by calling malloc() or calloc().
On a PC compatible, the same limitations apply, and more. You need to use at least a large data model. (See
the discussion at the beginning of the chapter.) You might also need to call “far” variants of malloc() or
calloc(). For example, with Borland C and C++ compilers, you could write
far char *buffer = farmalloc(70000L);
Or with Microsoft C and C++ compilers, you could write
far char *buffer = fmalloc(70000L);
to allocate 70,000 bytes of memory into a buffer. (The L in 70000L forces a long constant. An int constant
might be only 15 bits long plus a sign bit, not big enough to store the value 70,000.)

Cross Reference:

VII.18: What is the difference between far and near?
VII.21: What is the heap?
IX.3: Why worry about the addresses of the elements beyond the end of an array?

No comments:

Post a Comment