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
34
35
36
37
38
39
40
41
42
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>

// From office hours 2/20/2023

int main(int argc, char* argv[]) {
    // Q: Why can't I do `string[idx] = separator;`?    
    
    // Suppose we were joining strings={"ab","cd"} with delimiter="-";
    char* strings[] = {"ab", "cd"};
    char* separator = "-";
    int s_len = 6;
    char* s = malloc(*s * s_len);
    s[0] = strings[0][0];  // 'a'
    s[1] = strings[0][1];  // 'b'

//  s[2] = separator;  // Why can't I do this?
//  └┬─┘   └───┬───┘
//  char      char*    // These types are NOT compatible

    // separator is the address of the '-', not the '-' itself.
    
    // If you knew the separator would only be one character, then you could do
    s[2] = separator[0];
//  char      char    // These types ARE compatible
    // BUT.... This would not work for longer separators.
    //
    // For most students in the class right now, the easiest and simplest way is a for loop.
    int s_idx = 2;
    for(int i = 0; i < strlen(separator); i++) {
        s[s_idx] = separator[i];
        s_idx++;
    }

    // If comfortable with memcpy, you could use this:
    memcpy(s + s_idx, separator, strlen(separator));

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

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