Created
October 21, 2023 06:11
-
-
Save devansh42/47f2d780b635edfc7b37c603013a8b0b to your computer and use it in GitHub Desktop.
Boring Dynamic String Implementation in C
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" | |
// HEADER_SIZE would help us to move pointer to and fro | |
// usually, sizeof(unsigned int) is 4 bytes | |
// so this will be 8 bytes | |
#define HEADER_SIZE 2 * sizeof(unsigned int) | |
struct DynamicStr | |
{ | |
unsigned int len; | |
unsigned int capacity; | |
char data[]; | |
}; | |
typedef struct DynamicStr DStr; // To make our life easier | |
DStr *newString(const char *data) | |
{ | |
DStr *new_str; | |
int len = strlen(data); | |
int struct_size = HEADER_SIZE + len + 1; | |
new_str = (DStr *)malloc(struct_size); // Allocate memory for struct | |
new_str->len = len; | |
new_str->capacity = len; | |
memcpy(new_str->data, data, len); // Copy source string content to new string | |
new_str->data[len + 1] = '\0'; // Adding a null terminator | |
return new_str; | |
} | |
unsigned int len(DStr *d) | |
{ | |
return d->len; | |
} | |
int main() | |
{ | |
DStr *new_str = newString("Hello World"); | |
printf("Dynamic String: %s", new_str->data); | |
printf("Dynamic String Length: %u", len(new_str)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment