c-template
random.c
Go to the documentation of this file.
1 #include <stdlib.h>
2 #include <assert.h>
3 #include "../../include/utils/random.h"
4 #include "../../include/utils/errors.h"
5 #include "../../include/utils/returns.h"
6 
7 cg_return *get_random_string(int stringLength) {
8  // allocate a chunk of memory sized to stringLength
9  // not sure why its showing an error in vscode???
10  // https://stackoverflow.com/questions/50557000/complie-error-in-c-program-visual-studio-regarding-malloc-a-value-of-type-vo?rq=1
11  char *retWord = malloc(stringLength);
12  if (retWord == NULL) {
13  return new_cg_return(NULL, new_cg_error("failed to malloc memory"));
14  }
15  // assign each char from word to its corresponding vlaue in retWord
16  for (int i = 0; i < stringLength; i++) {
17  retWord[i] = letters[get_random_number(0, 25)];
18  }
19  return new_cg_return(retWord, NULL);
20 }
21 
22 int get_random_number(int lower, int upper) {
23  return (rand() % (upper - lower + 1)) + lower;
24 }
letters
const char letters[26]
Definition: random.h:8
new_cg_error
cg_error * new_cg_error(char *message)
returns a cg_error struct containing message
Definition: errors.c:7
new_cg_return
cg_return * new_cg_return(void *value, cg_error *err)
creates a new cg_return struct
Definition: returns.c:5
get_random_number
int get_random_number(int lower, int upper)
Definition: random.c:22
cg_return
allows returning both a value and error message from a function call useful as it makes it easier to ...
Definition: returns.h:14
get_random_string
cg_return * get_random_string(int stringLength)
Definition: random.c:7