1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <stdio.h>
#include <stdlib.h>

// Note for HW06:  If you have conditional jump based on uninitialized
// value, there's a very good chance you forgot to write the '\0' at the
// end of your string.  Make sure you understand why this error happens.

char* mystrdup(char* s) {
    // Find LENGTH
    size_t len = 0;
    while(s[len] != '\0') { // while(…) { … } is a kind of conditional jump
        len++;
    }

    // ALLOCATE memory for new string
    char* new_s = malloc(len * sizeof(*new_s)); // Don't forget '*'

    // POPULATE new string with characters, including the null terminator
    for(int i = 0; i < len; i++) {
        new_s[i] = s[i];
    }
    new_s[len] = '\0';  // Don't forget the null terminator!!!
    return new_s;
}

int main(int argc, char* argv[]) {
    char* s1 = mystrdup("protein");
    printf("s1 == \"%s\"\n", s1);
    free(s1);

    return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

© Copyright 2020 Alexander J. Quinn         This content is protected and may not be shared, uploaded, or distributed.