C Program: Length of String (w/ Pointers)

There already were two simple C programs we wrote earlier to find the length of a given string, with and without the use of strlen() function.

Here, we will be making use of pointers to compute their length.

c program string length

Strings are made up of characters, and in our previous examples we made use of character arrays to initialize and store them. Now we will be using character pointers instead.

We declare a pointer *text of type char and create a string literal 'HELLO' in the memory. Look at it again in two parts: char *text creates a character pointer and text = "HELLO" creates a string literal in the memory. The character pointer *text points to the first character of the string 'HELLO'. We declare another character pointer *p and assign to it the address of the first character of text .

The while loop loops till the value at address encounters the null character \0, which indicates the end of the string. Note that the format specifier for pointer type is %p. While the pointer *p gets incremented inside the while loop, the first pointer text remained unchanged and still points to the address of the first character. Therefore, the difference (p - text) yeilds the length of the given string.

				
				#include <stdio.h>

				int main() {
					char *text = "HELLO";
					int length;
					char *p = text;

					while(*p != '\0') {
						printf("The address of %c is at %p\n", *p, p);
						p++;
					}

					length = p - text;
					printf("Length of the string '%s' is %d", text, length);

					return 0;
				}
				
			

The above program gives the following output.

				
					The address of H is at 0x10acd0f72
					The address of E is at 0x10acd0f73
					The address of L is at 0x10acd0f74
					The address of L is at 0x10acd0f75
					The address of O is at 0x10acd0f76
					Length of the string 'HELLO' is 5