From 5ff1e0a1878bd658a8ce385e01b74d9b553d95a9 Mon Sep 17 00:00:00 2001 From: bronifty Date: Mon, 14 Oct 2024 01:10:27 -0400 Subject: [PATCH] this --- docs/courses/cs50/c.mdx | 47 +++++++++++++++++++++++++++++++++++------ 1 file changed, 40 insertions(+), 7 deletions(-) diff --git a/docs/courses/cs50/c.mdx b/docs/courses/cs50/c.mdx index e4a748f..162012d 100644 --- a/docs/courses/cs50/c.mdx +++ b/docs/courses/cs50/c.mdx @@ -266,6 +266,7 @@ int main(void) { ```c +// balanced-tree.c #include #include #include @@ -387,14 +388,41 @@ void free_bst(node *root) { int main(int argc, char *argv[]) { if (argc < 2) { - printf("Usage: %s \n", argv[0]); - printf("Example: %s 5 3 1 4 2\n", argv[0]); - return EXIT_FAILURE; + int predefined_numbers[] = {54, 1, 22, 9, 7, 6, 88, 44, 22, 30, 1, 3, 5, 7, 9, 6, 2, 4}; + int num_elements = sizeof(predefined_numbers) / sizeof(predefined_numbers[0]); + + argc = num_elements + 1; // +1 for the program name + char **new_argv = (char **) malloc(argc * sizeof(char*)); + if (new_argv == NULL) { + perror("Failed to allocate memory for new argv"); + return EXIT_FAILURE; + } + + new_argv[0] = argv[0]; // Program name + for (int i = 0; i < num_elements; i++) { + char *num_str = (char *) malloc(12 * sizeof(char)); // Enough for any 32-bit integer + if (num_str == NULL) { + perror("Failed to allocate memory for number string"); + return EXIT_FAILURE; + } + /* + * makes the i+1th element of new_argv point to the + * memory location where the string representation of a number is stored. + */ + snprintf(num_str, 12, "%d", predefined_numbers[i]); + /* + * after new_argv[i + 1] = num_str; , + * the i-th + 1 element of new_argv is supplied with + * the ith element of the loop converted to a string + */ + new_argv[i + 1] = num_str; + } + + argv = new_argv; } node *bst_root = NULL; // Root of the BST - // Parse command-line arguments and insert into BST for (int i = 1; i < argc; i++) { char *endptr; errno = 0; // To distinguish success/failure after the call @@ -431,11 +459,18 @@ int main(int argc, char *argv[]) { // Free allocated memory free_bst(bst_root); + if (argc > 1) { + for (int i = 1; i < argc; i++) { + free(argv[i]); + } + free(argv); + } + return EXIT_SUCCESS; } /** - * /usr/bin/clang++ -std=c++17 -g ./balanced-tree.c -o ./balanced-tree + * /usr/bin/clang -std=c17 -g ./balanced-tree.c -o ./balanced-tree * ./balanced-tree 54 1 22 97 6 88 44 22 30 1 3 5 7 9 6 2 * In-order traversal of the BST: * 1 1 2 3 5 6 6 7 9 22 30 44 54 88 97 @@ -446,6 +481,4 @@ int main(int argc, char *argv[]) { * Number 4 is found in the tree. **/ - - ```