Skip to main content

Dynamic Allocation of an Array of Strings in C.

   https://www.geeksforgeeks.org/how-to-create-a-dynamic-array-of-strings-in-c/

In C, dynamic arrays are essential for handling data structures whose size changes dynamically during the program’s runtime. Strings are arrays of characters terminated by the null character ‘\0’. A dynamic array of strings will ensure to change it’s size dynamically during the runtime of the program as per the user’s needs. In this article, we will learn how to create a dynamic array of strings in C.

Create a Dynamic Array of Strings in C

To create a dynamic array of strings in C, we can use the concept of double pointer and dynamic memory allocation. The double pointer is the pointer that stores the memory address of another pointer. We create an array of pointers to characters (i.e. strings) and then store the address of this array in the double-pointer to characters. Each of the pointer to the character is again allocated memory based on the size of the string it is storing.

Approach

  • Initialize a double pointer to store an array of strings.
  • Allocate memory for the initial size of the array using the malloc function.
  • Each element in the array will be a pointer to a string.
  • For each pointer in the array, allocate memory for the string using the malloc function.
  • Use the sprintf function to assign value to the string in the array.
  • Free memory for each string using the free function.
  • Free memory for the whole array of pointers using the free function.

Note: We have to first free() the memory allocated to each of the pointer of the array and then free the array of pointers. Otherwise, it may lead to the memory leak.

C Program to Create a Dynamic Array of Strings

The following program illustrates how to create a dynamic array of strings in C:

 

// C Program to illustrate how to create a dynamic array of
// strings
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// define the maximum length of the string you will store in
// the array
#define MAX_STRING_LENGTH 20

int main()
{
    // Initialize a double pointer to store the array of
    // strings
    char** strings = NULL;
    // Declare the initial size of the dynamic array
    int size = 5;

    // Allocate memory for the array of strings
    strings = (char**)malloc(size * sizeof(char*));
    if (strings == NULL) {
        fprintf(stderr, "Memory allocation failed\n");
        return 1;
    }

    // Allocate memory for each string and assign values
    for (int i = 0; i < size; i++) {
        // Allocate memory for each string
        strings[i] = (char*)malloc((MAX_STRING_LENGTH + 1)
                                   * sizeof(char));
        if (strings[i] == NULL) {
            fprintf(stderr, "Memory allocation failed\n");
            return 1;
        }
        // Assign values to each string
        sprintf(strings[i], "Student%d", i);
    }

    // Print the strings present in the array
    for (int i = 0; i < size; i++) {
        printf("%s\n", strings[i]);
    }

    // Free memory for each string
    for (int i = 0; i < size; i++) {
        free(strings[i]);
    }
    // Free memory for the array of pointers
    free(strings);

    return 0;
}
 

Comments

Popular posts from this blog

Gnocl Dashboard

Over the past few programming sessions I've been working on producing a central point, a dashboard, around which it's possible to see the various Gnocl widgets and commands in operation. In many ways like the demo script which shipped with the earlier releases of Gnocl but offers much more. The introspection functionality provides details of the various options and sub-commands of each Gnocl procedure which are displayed under the associated tab. Sample scripts are included for each item which offers newcomers a clearer insight into how make the most of what's on offer.

gnocl::calendar

Given this module some attention today. Added some of the more package wide options to the module and created customised handler for setting the month. (For some odd reason months are are counted 0-11 whereas days are 1-31.) There's still a little more to do to this one including the addition of code to store diary details. Here's the working test script to show the range of options at work. The percentage substitution string item %e explores something that I've been toying with, the name of the signal/event that initiated the call. Ok, a script can keep its own internal trace but who knows, it might prove useful. #--------------- # calendarTest.tcl #--------------- # Author:   William J Giddings # Date:     07/05/09 #--------------- #!/bin/sh # the next line restarts using tclsh \ exec tclsh "$0" "$@" #--------------- package require Gnocl set cal [gnocl::calendar] $cal configure -day 8 -month 7 -year 1956 $cal configure -rowHeight 1 -colWidth 1 $ca

Getting Widget Style Properties

Until the move over to Gtk4, Gnocl is still built against the Gtk 2.21 libraries. One of the inconveniences of Gtk is getting and setting widget style settings which are considered to be set globally by the desktop style settings and not for the programmer to tinker around with. Needless to say, there are times when different defaults are preferred, largely to draw the users attention to 'something a bit different'. The function gtk_widget_modify_font  is a convenience function to set the widget basefont as shown in this snippet from the button.c module,  if ( options[baseFontIdx].status == GNOCL_STATUS_CHANGED ) { GtkWidget *label; label = gnoclFindChild ( GTK_WIDGET ( para->button ), GTK_TYPE_LABEL ); PangoFontDescription *font_desc = pango_font_description_from_string ( Tcl_GetString ( options[baseFontIdx].val.obj ) ); gtk_widget_modify_font ( GTK_WIDGET ( label ), font_desc ); pango_font_description_free ( font_desc ); } Unfortunately, there's no d