202 Intermediate C Programming
int main ( i n t argc , char * argv [])30
{31
i f ( argc != 2)32
{33
return EXIT _FAILUR E ;34
}35
int n = ( i n t ) strtol ( argv [1] , NULL , 10) ;36
i f (n <= 0)37
{38
return EXIT _FAILUR E ;39
}40
int * arr ;41
arr = malloc ( s i z e o f ( i nt ) * n) ;42
partition ( arr , 0, n );43
free ( arr );44
return EXIT _SUCCES S ;45
}46
The partition function is the core of this program. This function takes three arguments:
1. arr is an integer pointer. It is an array that stores the numbers used in a given
partition.
2. ind is an integer. It is an index of the array. The value indicates where the next
element will be written. It also gives the length of the partition so far.
3. left is an integer. It is the remaining value to be partitioned.
The return at line 21 is unnecessary. When left is zero, the function will not enter the
for loop. Adding this return makes the program easier to read.
When main calls partition, ind is zero—the index of the first element of the array. The
value left is the remaining value to be partitioned. Even though this program is short, it
reviews many important concepts explained earlier. Thus, it is worth explaining in detail.
14.1 Stack and Heap Memory
Suppose the value of n is 4. The following table shows the stack and heap memory after
running line 42 and before line 43. The table assumes that each integer occupies 4 bytes
(sizeof(int) is 4).
Frame Symbol Address Value
main
arr 101 10000
n 100 4
(a) Stack Memory
Symbol Address Value
arr[3] 10012 garbage
arr[2] 10008 garbage
arr[1] 10004 garbage
arr[0] 10000 garbage
(b) Heap Memory