Is there way how to make my string to even size?
EDIT: I need a few string in struct that have even length. So something like:
struct msg { char * first; char * second; char * third; };
so it is in the end something like first string "hi\\0\\0" second string "hello\\0" third string "byebye\\0\\0" and i need to change them anytime+they are dynamic allocated.
Create a strdup_even()
.
Allocate memory as needed to copy the string, plus maybe 1 more to make "even".
char *strdup_even(const char *str) {
size_t len = strlen(str) + 1; // Size needed for the _string_
size_t len2 = len + len % 2; // Even allocation size
char *copy = malloc(len2);
if (copy) {
memcpy(copy, str, len);
if (len2 > len) {
copy[len] = '\0';
}
}
return copy;
}
Sample usage
struct msg m;
m.first = strdup_even("hi");
m.second = strdup_even("hello");
Use malloc()
and realloc()
:
char *string = malloc(STRING_SIZE);
strcpy(string, "hi");
string = realloc(string, STRING_SIZE+1);
string[STRING_SIZE] = '\0';
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.