Created
October 24, 2018 08:17
-
-
Save acoshift/60be0278466266f8860cd16b9175256f to your computer and use it in GitHub Desktop.
Go string in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#include <stdlib.h> | |
typedef struct { | |
char *str; | |
int len; | |
} string; | |
string appendString(string s1, string s2) { | |
string r; | |
r.len = s1.len + s2.len; | |
r.str = malloc(sizeof(char) * r.len); | |
memcpy(r.str, s1.str, sizeof(char) * s1.len); | |
memcpy(r.str + sizeof(char) * s1.len, s2.str, sizeof(char) * s2.len); | |
return r; | |
} | |
void sayHello(string name) { | |
printf("Hello, %.*s\n", name.len, name.str); | |
} | |
void mutateString1(string s) { | |
s.len = 10; | |
s.str = malloc(sizeof(char) * s.len); | |
memcpy(s.str, "John Titor", sizeof(char) * s.len); | |
} | |
void mutateString2(string *s) { | |
s->len = 10; | |
s->str = malloc(sizeof(char) * s->len); | |
memcpy(s->str, "John Titor", sizeof(char) * s->len); | |
} | |
int main() { | |
string myName; | |
myName.len = 8; | |
myName.str = malloc(sizeof(char) * myName.len); | |
memcpy(myName.str, "acoshift", sizeof(char) * myName.len); | |
sayHello(myName); | |
mutateString1(myName); | |
sayHello(myName); | |
mutateString2(&myName); | |
sayHello(myName); | |
string n; | |
n.len = 9; | |
n.str = malloc(sizeof(char) * n.len); | |
memcpy(n.str, " IBM 5100", sizeof(char) * n.len); | |
string t = appendString(myName, n); | |
sayHello(t); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment