String and string pointer in C programming language

Source

String in C programming language is collection of characters whereas character in C is a single alphabet. For, example, ‘A’ is character (in C we uses single quote to assign any character to char variable) and “STRING” is a string (in C we uses double quote to assign any string to string variable).

Now one question will be there in your mind that does C language has string datatype? And answer is no. Unlike C#, Java and other language, C doesn’t have string datatype. But that doesn’t mean that you cannot store string in C. There is other way to store string in C let me explain you how.

All of you must have heard about array in C (if not then you can my C lesson on array and its type like 2D array and 3D array), we can use array to store string. In other words, we can use character array to store string. I know it is quite confusing, don’t worry I will explain everything. Let’s take one simple example for better understanding of string.

String in C program example

#include "stdio.h"
#include "conio.h"

int main()
{
	char str[6] = "STRING";
	int i;
	clrscr();

	for(i=0; str[i] !='\0'; i++)
	{
		printf(" %c stored @ address : %u\n",str[i], &str[i]);
	}

	getch();
	return 0;
}

String in C example output

Source

String program example explanation

If you have good understanding about array then it’s going to be very easy for me to explain above C program example, if you are not that confident about array (knowledge of array declaration and usage would be enough) then I would suggest you to read my tutorial on array (click here to read it now).

In above program, we are initializing one character array to store a string and then with the help of for loop we are displaying that stored string.

In line no. 6, we are declaring and initializing one character array “str”. As it’s an array, so we have to provide its size i.e. 6 in our example. We have assigned “STRING” to “str” variable and this initialization has allocated memory space to store that string (memory mapping is given below). Memory address displayed in memory mapping may differ from PC to PC; on my PC it was like this.

Memory mapping of string in C

Source

In code block 10 – 13 we are looping “str” variable and displaying its content. Now check line no. 10 carefully, it’s a for loop, here we are assigning 0 to variable “i” and checking condition (str[i] !='\0') for loop execution. This condition checking might be confusing for you but it’s very simple. To understand this condition I would suggest you to check above memory mapping image. See the last cell value, it is ‘\0’ at address 65526. That is NULL character (some people call it terminating character also) and it is automatically inserted to every array in C.

So in for loop condition we are checking if current character is not equal to NULL character (‘\0’) then only print that character. We can make that for loop condition even simpler using following C statement and if you replaces above for loop with this one program will still work. But there are few problems with that approach. Suppose you have modified string in “str” variable to “RAJKISHOR” and as result character array size (size will be now 10) will get modified. Then below for loop will print partial string, because it will loop to 0 - 6 index of “str” array but you can modify below for loop condition to loop till 10th index but I don’t like making too many changes for simple things so I prefer dynamic approach. Hard coding loop condition (like below) will also create problem when we will take direct input from keyboard because you can’t guess how many character user will input. So always prefer dynamic approach.

Syntax: for(i=0; i<6; i++)

In printf statement (line no. 12) you can see that I am printing character with address so that I can show “str”array’s memory mapping.

I think that is enough explanation for that program, now I will try to make it more simple and dynamic.

String in C example

#include "stdio.h"
#include "conio.h"
#include "string.h"

int main()
{
	char str[] = "STRING";
	int i;
	clrscr();

	for(i=0;i<strlen(str);i++)
	{
		printf(" %c stored @ address : %u\n",str[i], &str[i]);
	}

	printf("\n\n Simple way of printing string.\n\n");
	printf(" %s stored @ address : %u\n",str, &str);

	getch();
	return 0;
}
Source

C example explanation

This example is similar to first example with slight change in string printing logic and you can see that change in line no. 11. In that for loop condition part we are using “strlen()” function to calculate length of string (i.e. i<strlen(str)). In our program “strlen()” function will return 6 because “STRING” string is 6 character long. And based on this length we are looping the array and printing the character along with address. There is one more important point in this program, to use “strlen()” in your program you have to “string.h” (see line no. 3 in above program).

Now it’s time for one line code to print string, some of you might be thinking why this guy is telling easiest way of printing string in the last. That is because you should know all the tricks and I think if I’ll tell you easiest at the beginning then you will not be interested in learning other way (or I should say difficult one). Those examples will help you when you will write program for string reverse and palindrome etc.

Let’s concentrate on line no. 13; this is the easiest method to print string in C. We can use “%s” format to print string in C. And rest of the code is already explained to you.

Please note it that address of array will not be same on your PC and it will differ from PC to PC.

String pointer in C

The way we use character array to store strings similarly we can use character pointer to store string and it’s a good practice to use pointer rather than array. In array we have to define the size of array before we can use it but in pointer there is no such requirement. You can read my C lesson on pointer if you have any doubt about pointer.

String pointer in C example

#include "stdio.h"
#include "conio.h"

int main()
{
	char *str = "STRING POINTER";
	int i = 0;
	clrscr();

	while(*(str + i) !='\0')
	{
		printf("%c", *(str +i));
		i++;
	}
	printf("\n");

	puts(str);
	printf("%s", str);

	getch();
	return 0;
}
Source

C example explanation

In above example we have one character pointer (line no. 6str”) and which is initialized with string “STRING POINTER”. Next I tried to display that stored string in different ways. Let’s begin with first code block where we will use loop to display string. Line no. 10 contains while loop which loops through string pointer, in this line we are checking whether current memory location value is NULL (‘\0’) or not. This line (*(str + i) !='\0') might be little confusing if you don’t have any knowledge about pointer. Let me explain this line for you.

As you know “*str” is character pointer and simply “str” means 0th location of that string, so when we type (*(str+i)), this statement will give us “S” from “STRING POINTER”. Still thinking how? Assume that “str” pointer starting address is “65550” then “65550 + 0” (as initial value of i is 0) will point to “S” and in same way “65550 + 1” will point to “T”. Next we are using “Value at address” operator (*) to get value stored in that address. I think this much explanation for that line would be enough.

So in while loop condition we are checking whether the value of that memory location is NULL or not. If value is not NULL then print that value or exit from while loop. Simple logic isn’t it?

Now come to line no. 17, you might find one new function “puts” here. We use “puts” to output any string and this is quite different from “printf” function. Firstly you cannot format output; I mean it takes only one parameter whereas “printf” takes multiple parameters and you can append text along formats. Secondly, “puts” appends newline (‘\n’) character at the end of output. You can see that in output, after while loop block I used newline character in line no. 15 but in case of “puts” there is no newline character in next line.

I don’t think I need to explain line no. 18 as I have already explained that in previous program.

Reading string in C

Sometime in your program you may want to read string from keyboard and it is very fundamental thing which every programming language including C programming language has. This feature helps a developer and programmer to write user friendly and user interactive programs. Just imagine Notepad application without keyboard input; will that be useful from any point of view? So if you are going to be part of any real life software development project then it is obvious that you application will have user interactivity and lots of data inputted by user.

To explore this feature of C language we will write a simple C program which will ask user to provide their name and it will greet user.

Reading string in C using scanf function

#include "stdio.h"
#include "conio.h"

int main()
{
	char str[30];
	clrscr();
	printf("Enter your first name : ");
	scanf("%s", str);
	printf("\n\nWelcome to C language %s", str);

	getch();
	return 0;
}
Source

C example explanation

In above example we have one character array “str” of size 30 and we will use it to store name given by user in runtime (when program is running). To read a string in C we will use “scanf” function, see the line no 9. In this line we are using “%s” to read string and that string will be stored in “str” character array. To display value stored in that array we can use “printf” function (see line no. 10), note that to display string we are using “%s” format. Don’t you think it’s very simple to read and display string in C from keyboard?

But did you notice one error in output? I had given “raj kishor” as input but it’s displaying “raj” in output; but why? Ah this is really confusing. Let’s verify what the reason behind it is.

As you guys know like “printf” function, “scanf” function can take many arguments and “scanf” function uses space character to differentiate parameters. So in our example we had “raj kishor” and it took “raj” & “kishor” as two different arguments. So it stored “raj” in “str” array and kept “kishor” word for other array which is not provided. If I will give input as “rajkishor” then it will display “rajkishor” in output. But we can’t write our name without space, so how we can store our name display it. Don’t worry we have workaround for that and I will show you same example with that workaround.

Reading string in C using scanf function

#include "stdio.h"
#include "conio.h"

int main()
{
	char str[30];
	clrscr();
	printf("Enter your first name : ");
	scanf("%[^\n]s", str);
	printf("\n\nWelcome to C language %s", str);

	getch();
	return 0;
}
Source

C example explanation

This example is same as above one with only one difference in line no 9. In this line we have slightly modified string format for “scanf” function from “%s” to “%[^\n]s”. This new modification will tell compiler to take input for “scanf” function till user hits “Enter”. So we will have all user input in “str” array.

Reading string in C using gets function

#include "stdio.h"
#include "conio.h"

int main()
{
	char str[30];
	clrscr();
	printf("Enter your first name : ");
	gets(str);
	printf("\n\nWelcome to C language %s", str);

	getch();
	return 0;
}
Source

C example explanation

In above example also we are reading string from keyboard but this time we are using “gets” function (line no. 9). This is the only difference in comparison of last two C program.

Let me explain you about “gets” function of C language. If we compare “gets” function with “scanf” function then we have two major differences. First is “gets” function can take only one string at a time, see line no 9 where we are passing “str” in “gets” function. And second is, it can read multi word string (I know we have workaround for this in “scanf” function but). Please see the output where I entered “raj kishor” as first name and it displayed “raj kishor”.

So in this way we can read string in C, which method you will use that depends on you. But I would suggest you to explore all the methods to read and display string in C.

Your opinion

Did this help you to learn about string in C programming and its concept?

See results without voting

More by this Author


Comments 2 comments

Jamal 4 years ago

brilliant explanation very easy to understand but i was hoping to see some fgets and fputs and others along those lines but never the less this is very useful

thank you


bipendra saw 4 years ago

how to count word

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working