ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

String and String Pointer in C Programming Language

Updated on July 7, 2018
rajkishor09 profile image

Raj is an ardent coder who loves exploring new technology. He is an IT pro with over a decade of experience in C#, Angular, React, and Vue.

learn string programs in c
learn string programs in c

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 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;
}
output of string program
output of string program

Code 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 language
memory mapping of string in C language

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;
}
output of string program in c language
output of string program in c language

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;
}
String pointer in C example output
String pointer in C example output

Code 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;
}
reading string in C program using scanf
reading string in C program using scanf

Code 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;
}
another way to read string in c program using scanf
another way to read string in c program using scanf

Code 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.

Read String in C Program With 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;
}
reading string in C program with gets function
reading string in C program with gets function

Code 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
working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://corp.maven.io/privacy-policy

Show Details
Necessary
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Marketing
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Statistics
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)