Skip to content

Commit

Permalink
this
Browse files Browse the repository at this point in the history
  • Loading branch information
bronifty committed Oct 14, 2024
1 parent 74ef51d commit 5ff1e0a
Showing 1 changed file with 40 additions and 7 deletions.
47 changes: 40 additions & 7 deletions docs/courses/cs50/c.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,7 @@ int main(void) {
```c
// balanced-tree.c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
Expand Down Expand Up @@ -387,14 +388,41 @@ void free_bst(node *root) {
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: %s <numbers...>\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
Expand Down Expand Up @@ -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
Expand All @@ -446,6 +481,4 @@ int main(int argc, char *argv[]) {
* Number 4 is found in the tree.
**/
```

0 comments on commit 5ff1e0a

Please sign in to comment.