Holla Tech - Learn

Allocating Memory for Strings
 

When allocating memory for a string pointer, you may want to use string length rather than the sizeof operator for calculating bytes.
Consider the following program: 

char str20[20];
char *str = NULL;

strcpy(str20, “12345”);
str = malloc(strlen(str20) + 1);
strcpy(str, str20);
printf(“%s”, str);

 

This approach is better memory management because you aren’t allocating more space than is needed to a pointer. When using strlen to determine the number of bytes needed for a string, be sure to include one extra byte for the NULL character ‘\0’.
A char is always one byte, so there is no need to multiply the memory requirements by sizeof(char). 


Dynamic Arrays
 

Many algorithms implement a dynamic array because this allows the number of elements to grow as needed.
Because elements are not allocated all at once, dynamic arrays typically use a structure to keep track of current array size, current capacity, and a pointer to the elements, as in the following program.

typedef struct {
  int *elements;
  int size;
  int cap;
} dyn_array;

dyn_array arr;

/* initialize array */
arr.size = 0;
arr.elements = calloc(1, sizeof(*arr.elements) );
arr.cap = 1;  /* room for 1 element */ 

 

To expand by more elements:

arr.elements = realloc(arr.elements, (5 + arr.cap) * sizeof(*arr.elements));
if (arr.elements != NULL)
  arr.cap += 5; /* increase capacity */ 

 

Adding an element to the array increases its size:

if (arr.size < arr.cap) {
  arr.elements[arr.size] = 50;
  arr.size++;
} else {
  printf("Need to expand the array.");

 

NOTE!
The entire program is written in main() for demonstration purposes. To properly implement a dynamic array, sub-tasks should be broken down into functions such as init_array(), increase_array(), add_element(), and display_array(). The error checking was also skipped to keep the demo short.

BACK NEXT

CLICK ON THE BUTTON BELOW TO GO TO THE C MAIN COURSE PAGE. 

C MAIN COURSE PAGE

 


© License: All Rights Reserved 


CONTACT HOLLA TECH – LEARN SUPPORT