Created
January 4, 2015 10:44
-
-
Save banthar/07b7d13f1dae4cfe1c92 to your computer and use it in GitHub Desktop.
This file contains 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 { | |
int len; | |
char *s; | |
} string_t; | |
typedef string_t string; | |
void set(string* s1, char *s); | |
void concat(string* s1, string* s2); | |
void stringFree(string* s1); | |
int main(void) { | |
string str1 = {0}; | |
string str2 = {0}; | |
set(&str1,"hello "); | |
set(&str2,"world!"); | |
concat(&str1,&str2); | |
printf("%p , %s\n",str1.s,str1.s); | |
stringFree(&str1); | |
stringFree(&str2); | |
} | |
void set(string* s1, char *s){ | |
free(s1->s); | |
s1->s = strdup(s); | |
s1->len = strlen(s); | |
} | |
void concat (string* s1, string* s2){ | |
int totalLen = s1->len + s2->len; | |
char rslt[totalLen+1]; | |
int i=0; | |
for(i=0;i<s1->len;i++){ | |
rslt[i] = s1->s[i]; | |
} | |
for(i=s1->len;i<totalLen;i++){ | |
int j=i-s1->len; | |
rslt[i] = s2->s[j]; | |
} | |
rslt[totalLen] = '\0'; | |
set(s1,rslt); | |
} | |
void stringFree(string* s1) { | |
free(s1->s); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment