Wednesday, August 07, 2024

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;
}
 

Monday, July 15, 2024

Overhaul of widget cget functionality.

The current basis of the cget function for widgets is based upon code written over 20yrs ago and, whilst it works reasonably well for the simple setting of gtk widget properties, support for more complex custom options is hit and miss.

 

typedef struct GnoclOption_ {
    const char *optName;  
    enum GnoclOptionType type;
    const char *propName;
    gnoclOptFunc *func;
    const char *args;
    const char *description;
    const char *values; 
    enum GnoclOptionStatus status;
    union {
        gboolean b;
        gint     i;
        gdouble  d;
        gchar    *str;
        Tcl_Obj  *obj;
        } val;
} GnoclOption;

 

With the recent updating of the C sources which includes an expansion of the GnoclOption structure to accommodate documentation support, it well worth reviewing the way in which widget functions handle the return of options.

Rather than treating the retrieval of properties set by a function as the final call, perhaps it should be prioritized. If one is not present, then extract a value based upon the setting type. 

 case CgetIdx: {
 int     idx;

/* get the idx of the option in structure array */
Tcl_GetIndexFromObjStruct ( interp, objv[2], ( char ** ) &options[0].optName, sizeof ( GnoclOption ), "option", TCL_EXACT, &idx );

/* does the option have a function? */
if (options[idx].func != NULL) {
    Tcl_Obj *res;
    options[idx].func ( interp, &options[idx], grid, &res );
    Tcl_SetObjResult ( interp, res );
} else {
    switch ( gnoclCget ( interp, objc, objv, G_OBJECT ( grid ), options, &idx ) ) {
      case GNOCL_CGET_ERROR: { return TCL_ERROR; }
      case GNOCL_CGET_HANDLED: { return TCL_OK; }
      case GNOCL_CGET_NOTHANDLED: {
           return cget ( interp, grid, options, idx ); }
  }
}
break;
}
return TCL_OK;
}


Placing this test at the head of the sequence is more intuitive as these provide the greates complication when dealing with extraction of settings.

A GnoclOpFun woudl then be something along the lines of:


static int gnoclOptBaseLineRow ( Tcl_Interp * interp, GnoclOption * opt, GObject * obj, Tcl_Obj **ret )

{

gint idx;

Tcl_GetIndexFromObj ( interp, opt->val.obj, baseLinePositions, "baseLinePosition", TCL_EXACT, &idx );

if ( ret == NULL ) { /* set value */

g_object_set ( obj, opt->propName, idx, NULL );

} else { /* get value */

g_object_get ( obj, opt->propName, &idx, NULL );

Tcl_SetObjResult ( interp, Tcl_NewStringObj ( baseLinePositions[idx], -1 ) );

}

return TCL_OK;

}

Obtaining the index of value from an array of strings or an array of structures.

    

static char *options[] = {
        "-opt1", "-opt2", "-opt3",NULL
    };
static enum  optsIdx {
    opt1Idx, opt2Idx, opt3Idx
    }; 

gint idx;

/* obtain idx from an array of strings */
Tcl_GetIndexFromObj ( interp, objv[1], options, "option", TCL_EXACT, &idx );


/* obtain idx from array of structures, not an array of strings */
Tcl_GetIndexFromObjStruct ( interp, objv[1], ( char ** ) &commands[0].cmdName, sizeof ( GnoclCommand ), "command", TCL_EXACT, &idx );

Wednesday, May 29, 2024

Remove named items from a list

Sometimes you just want to trim down a list of items but you're not quite certain where the items are so its not possible to use lreplace or lremove directly as these require indices. In order to obtain these lsearch can be used. 

The following code example shows how wrap these operations into a single procedure call where mylist is the list to alter, and args a list of items to remove. The procedure returns a new list rather than modifying the original directly.

 proc remove {mylist args} {
    
    foreach value $args {
        set idx [lsearch -exact $mylist $value]
        set mylist [lreplace $mylist $idx $idx]
    }
    
    return $mylist
}

Thursday, October 19, 2023

Creating Footnotes in HTML Exports

Description yet to come....

 

 

<!DOCTYPE html>
<html>
<head> <title>Creating Footnotes</title> </head>
<body lang="en-GB" link="#000080" vlink="#800000" dir="ltr"><p style="line-height: 100%; margin-bottom: 0cm">
Note one<a class="sdfootnoteanc" name="sdfootnote1anc" href="#sdfootnote1sym"><sup>1</sup></a>,
note two<a class="sdfootnoteanc" name="sdfootnote2anc" href="#sdfootnote2sym"><sup>2</sup></a>.
Note THREE<a class="sdfootnoteanc" name="sdfootnote3anc" href="#sdfootnote3sym"><sup>3</sup></a>.
</p>
<p style="line-height: 100%; margin-bottom: 0cm">Comment.<!-- My comment. --></p>


<hr style="width:15%;margin-left:0">

<div id="sdfootnote1"><p class="sdfootnote"><a class="sdfootnotesym" name="sdfootnote1sym" href="#sdfootnote1anc">1</a>&emsp;Note
    1</p>
</div>
<div id="sdfootnote2"><p class="sdfootnote"><a class="sdfootnotesym" name="sdfootnote2sym" href="#sdfootnote2anc">2</a>&emsp;Note
    2</p>
</div>
<div id="sdfootnote3"><p class="sdfootnote"><a class="sdfootnotesym" name="sdfootnote3sym" href="#sdfootnote3anc">3</a>&emsp;Note
    THREE</p>
</div>
</body>
</html>

 

 

Thursday, October 12, 2023

Drawing a chessboard grid with graphic characters


╔═══╤═══╤═══╤═══╤═══╤═══╤═══╤═══╗
8 ║ │ │ │ │ │ │ │ ║
╟───┼───┼───┼───┼───┼───┼───┼───╢
7 ║ │ │ │ │ │ │ │ ║
╟───┼───┼───┼───┼───┼───┼───┼───╢
6 ║ │ │ │ │ │ │ │ ║
╟───┼───┼───┼───┼───┼───┼───┼───╢
5 ║ │ │ │ │ │ │ │ ║
╟───┼───┼───┼───┼───┼───┼───┼───╢
4 ║ │ │ │ │ │ │ │ ║
╟───┼───┼───┼───┼───┼───┼───┼───╢
3 ║ │ │ │ │ │ │ │ ║
╟───┼───┼───┼───┼───┼───┼───┼───╢
2 ║ │ │ │ │ │ │ │ ║
╟───┼───┼───┼───┼───┼───┼───┼───╢
1 ║ │ │ │ │ │ │ │ ║
╚═══╧═══╧═══╧═══╧═══╧═══╧═══╧═══╝
a b c d e f g h

Thursday, August 31, 2023

Simple Runtime Debugging Message Dialog

At times it's useful to see what values variables hold, or offer some pause point before the code goes elsewhere before causing havoc. Its possible to write output to the terminal but this can get lost in copious forms of other outputs, besides, there's no pausing the script execution either. The following proc creates a custom dialog which displays ad message along with the point in the calling script from which it was invoked.

## simple runtime debugging feedback dialog, alternative to console based gnocl::msg
# @param msg message to display
# @returns none
#
proc xxx::msg {txt} {

set frame [info frame -1]

append msg "Message:\n\n"
append msg "$txt\n\n\n"
append msg "Called from:\n\n"
append msg "Proc:\t[lindex [info level -1] 0]\n"
append msg "File:\t[file tail [dict get $frame file]]\n"
append msg "Line:\t[dict get $frame line]\n"

gnocl::dialog \
-type info \
-text $msg \
-title [lindex [info level 0] 0] \
-setSize 0.2
}

json_shell_utils.tcl