Introduction to Data Types in C
As we all know, C is a strongly typed language i.e., C is rich in data types and offers several data types to programmers to store and manipulate different types of data. Below is the List of Primitive Data types that are present in C.
Why C doesn’t support String as a Primitive data type
You may have noticed that unlike other programming languages such as Java, Python, etc. C does not support string as a primitive (or we can say intrinsic) data type. Strings in C are implemented and manipulated by using character arrays. A string is a sequence of characters that is terminated by a null character.
The reason is that C is a procedure-oriented language and there is no Object for String. During Compilation, everything in C has a fixed storage space. If the length of a String is unknown at compile time, the compiler won't know how much storage should give to the String.
Disadvantages of using character arrays instead of String?
Since arrays have a fixed size allocated during compile time. Below are the disadvantages of using character arrays instead of strings.
- If the size is less than needed during run time, it will cause a memory error.
- If the size is too large and most of the indexes of the array are empty, then it will be a waste of memory
Developing a Custom String type in C
Concepts used
Before developing a new user-defined string type in C. We must know some concepts. They are as follows,
- Pointers
Pointers are a derived data type in c which is used to store the address of another variable. They are widely used in memory allocation/deallocation, memory management, etc. Their size is independent of any data type.
- Functions
Functions are the building blocks of a C program. Every C program contains the main function. Besides C offers us rich header files of inbuilt functions as well as allows users to develop user-defined functions as per their requirements.
- Header Files
Header Files are those files that contain prototypes(declarations) of functions that are used to facilitate program logic. They are added using #include, which is a preprocessor directive before the compilation of the program. Please note that header files do not contain the main method. They are saved with .h extension.
- Typedef Keyword
Sometimes we need to give an existing datatype(be it primitive, derived, or user-defined) a new name for our convenience. C language offers programmer typedef keyword which is used to create an alias (similar name) of an existing datatype. In simple words, we can say that typedef is a keyword that is used to redefine an already existing variable.
Code Section
We will develop our code in two parts,
- Creating The Header File
- Creating The Demo Program
We will be using TurboC/C++ Compiler for the development environment. However, you can use any other compiler of your choice. Now let us start developing the custom string type. Follow the below steps and you are good to go.
STEP 1
Start TurboC/C++ and click on File Tab on Menu bar.
STEP 2
Click on New option and Enter the filename as MYSTRIING.H.
STEP 3
Your File will be created as the one shown below.
STEP 4
Start typing the following Code:
MYSTRING.H
typedefchar* string;
//extract() function
voidextract(stringstr,inta,intb){
chartempstr[201];
strcpy(tempstr,str);
while(a<=b){
printf("%c",tempstr[a]);
a++;}printf("\n");}
STEP 5
Your code will look like this:
STEP 6
Compile the file using Alt+F9 Button and Save it. Remember since this is a header file we are not going to run it.
STEP 7
Go to File Menu and again click New.
STEP 8
Now name your file as DEMO.C.
STEP 9
Start typing the following Code:
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include"mystring.h" //Including header file we built earlier
int choice, start, end; //global variable
void showMenu() {
string x; //notice that we are now using string as a datatype
while (1) {
printf("\n\n\t\t\tWELCOME TO \"mystring.h\" Demo Program.");
printf("\n\t\t\tPress 1 to find length of a string.");
printf("\n\t\t\tPress 2 extract a part of a string(i.e,substring).");
printf("\n\t\t\tPress 3 to Exit Demo.");
printf("\n\t\t\tMake your choice:\t");
scanf("%d", & choice);
switch (choice) {
case 1:
printf("\n\t\t\tEnter Any String:\t");
fflush(stdin);
gets( & ( * x));
printf("\n\t\t\tYou've entered:%s", x);
printf("\n\t\t\tThe Given String contains %d characters.", strlen(x));
break;
case 2:
printf("\n\t\t\tEnter Any String:\t");
fflush(stdin);
gets( & ( * x));
printf("\n\t\t\tOriginal String is:%s", x);
printf("\n\t\t\tEnter start position:\t");
scanf("%d", & start);
printf("\n\t\t\tEnter end position:\t");
scanf("%d", & end);
printf("\n\t\t\tSubstring is:");
extract(x, start, end);
break;
case 3:
printf("\n\t\t\tExitting...");
delay(600);
exit(0);
break;
default:
printf("\n\t\t\tWrong choice Try Again");
}
}
}
void main() {
clrscr();
showMenu();
getch();
}
STEP 10
Your code will look like the one given below:
STEP 11
Compile your code using Alt+F9 key. In case there are no syntax errors it will show a dialogue box like this:
STEP 12
Now run your code using Ctrl+F9 key.
Congratulations you have successfully implemented string as a data type in C just like it exists in other languages such as C++, Java, Python, etc.
Code Explanation
With the fully working of the above code and its successful implementation, you will be curious about how actually the code is working i.e., what is exactly happening behind the scene. So, let us get started.
- First, we developed our own header file named “mystring.h”. In it, we have given a command which is
typedef char* string;
- Here we created an alias of char * which is a pointer to a character. In short, now we can refer to char* using the string keyword.
- The second thing which we did in that header file is that we defined a function named extract() which takes 3 arguments string x, start position, and end position.
- The function work as follows, it first copies the content of char *(referred by string) and then using start and end position arguments prints the substring (extracted string on screen).
- Now we have saved the header file and closed it.
- Now is the time to test whether now we are able to use string as a datatype directly or not i.e., without using character arrays. Hence we created a file named “Demo.C”.
- There we imported our header file and declare and used strings as we use in Java.
- Now we have created a menu-driven program here. Here you can see we have taken user input as gets(&(*x)).
- Actually here we are accessing the memory location pointed by our string i.e,(char * x), and using the gets() function(predefined in string.h) we have taken input from the user. After Successful Compilation, we see that our code is working fine.
- Congratulations we have successfully developed a string type in C (that too in a Procedural Oriented Language).
Conclusion
Here we saw that using pointers and other techniques, we can design and implement our own desired data types. Not only this but also we can design our own header files and use them in our program.