If we go and search for "string type in C" on internet or ask AI, we get a line saying "C has no string type".
I know, we get results like:
Most of the tutorials tell how to use a char array for strings but no one tells us how to build a string type using structs and heap allocation.
So here is simple string type:
First, the code!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char* s;
size_t len;
size_t cap;
} string;
void panic(char* message){
puts(message);
exit(1);
}
string string_new(char* text){
if(text == NULL) panic("error: NULL passed to string_new()");
string s = {0};
s.len = strlen(text);
s.cap = sizeof(char)*(s.len+1);
s.s = malloc(s.cap);
if(s.s == NULL){
panic("error: Memory allocation failed!");
}
strcpy(s.s,text);
return s;
}
void string_free(string* s){
if(s == NULL) return;
s->len = 0;
s->cap = 0;
free(s->s);
s->s = NULL;
}
int main(void){
string name = string_new("King Nyaomaru");
printf("Welcome %s!\n",name.s);
string_free(&name);
return 0;
}
Explanation
- First, the main function is the main function from where the program starts.
- This program does these things:
- Create a string, that is, instance of the struct type string, that we have at the top of the program.
- Format and print the welcome message using our string name. Yep, I followed the Necoz tradition!
- Then free the string's memory using its free function.
- Return 0, that is success!
string struct
Its a simple struct that has three things:
- s (char* pointer that will hold the address to a heap memory location where we put the data (characters)
- len (It will store how many characters the s field has currently
- cap (The total amount of memory, in bytes, allocated that
spoints to)
I will leave the string creation and freeing details to the next posts!
This is a basic version. We can extend the string functions to append or prepend or resize and all kinds of stuff are possible!
Acknowledgement
This is my first post under Necoz.
I want to thank @nyaomaru and @star123 for making me part of this wonderful org!

Top comments (2)
string_new("King Nyaomaru");🤣🤣🤣You're welcome, bro! To be honest, I understood the concept too. 😊❤️