String Array in C

Is there anyway to create a string array in C Language without predefined length of each string?
For example: I don’t want to declare char s[10][10000] for 10 strings of 10000 length, rather i want an array of length 10 and length of each string can be of any size.
I have my logic ready for the program but cannot execute(its working in DevC) as I made a 2d character array of huge size and get an error message SIGSEGV by codechef after submitting.
Note: I am new to C.

May be this.

C++ or pure C ?

This will work in case of c++ only.

A string in C is a pointer to a continuous segment of chars. You can declare a string using.

char* mystring;

This declares a pointer to a string. Now we need this pointer to point to a memory segment which will hold our string.

mystring = malloc(sizeof(char)*(stringlength + 1));

We have allocated 1 extra character for the Null termination or ‘\0’ which tells us that the string has ended.
Set each character using, mystring[index] = ‘character’; eg -> mystring[0] = ‘a’, mystring[1] = ‘b’ and so on. But REMEMBER to set the last character to ‘\0’. -> mystring[stringlength] = ‘\0’;
But what I have told you has a fixed size. To change the string to some other size first we will free the memory we had allocated and get some new memory allocated. Here is how it is done -

free(mystring);
mystring = malloc(sizeof(char)*(newstringlength + 1));

This new power you have acquired of have a dynamic string come at a price. You will need to be EXTREMELY CAREFUL about the memory you have. NEVER forget to free the memory once you have finished using it. If you do your program will have memory leaks which are hard to debug and can crash your program at unexpected times. Read more on C dynamic memory allocation and study this material - http://cslibrary.stanford.edu/102/PointersAndMemory.pdf which teaches pointers and memory allocation to beginners.
Good Luck!

1 Like