String Pointer in C

Learn via video course
FREE
View all courses
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
Topics Covered

This C programming tutorial focuses on storing strings using pointers. Strings in C are character arrays with a null character (\0) marking the end. Strings allow efficient access to characters by index. The tutorial delves into the concept of string pointers, explaining how pointers aid in accessing string indices, providing insights into the efficient manipulation of string data.

Creating a String

Individual characters in C are enclosed within a single quote for example, 'a', 'b', 'c'. As explained in the previous section, a string is a collection of characters. To store a string in C, we can create an array and store them in these arrays.

Syntax

To store a string in an array, we need to declare a one-dimensional array. The characters in the string can be set at the time of array declaration or later by accessing individual indexes, as shown below.

For example, to store a string "String" in an array str

example-4-string

Notice that although our string "String" has only six characters, our str array is of size 7 (one more than size) to store an extra null \0 character, so the value of our str array is "String\0". Also, as shown in figure , each character takes 1-byte of the memory space.

Note: We don't have to explicitly add a null character in the string as the compiler automatically adds it.

We can also use string literal to set the value of arrays. A string literal is a sequence of characters enclosed in double quotation marks (" "). The below-mentioned example is a simple string literal

The compiler automatically adds an extra null character at the end of the string if it is not mentioned explicitly.

Instead of initializing each character individually, string literal can be used to set the value of character array like mention below

What happens if space for a null character is not allocated?

What will happen if we accidentally overwrite the null terminator in a string or try to do something like

If a string doesn’t have a null character, the compiler will still let the program pass without any error. A string is simply a collection of characters, and we need \0 only to identify the end of the string.

Having no terminator in your c-string will result in functions on the string not being able to determine the end of the string, which will cause some undefined behaviour. If we try to print the string, it might crash due to a segmentation fault, or maybe it reads random chars from memory that is located after the string until it eventually finds a null character.

Creating a Pointer for the String

When we create an array, the variable name points to the address of the first element of the array. The other way to put this is the variable name of the array points to its starting position in the memory.

We can create a character pointer to string in C that points to the starting address of the character array. This pointer will point to the starting address of the string, that is the first character of the string, and we can dereference the pointer to access the value of the string.

In this code mentioned above, the character pointer to string in C ptr points to the starting address of the array str.

Note: Pointer and array are not the same, and here pointer stores the starting address of the array, and it can be dereferenced to access the value stored in the address.

example-5-string

We can also understand this from the figure here: pointer ptr stores the location of the first index of the array str at memory location 1000, but the pointer itself is located at memory address 8000.

Accessing String via a Pointer

An array is a contiguous block of memory, and when pointers to string in C are used to point them, the pointer stores the starting address of the array. Similarly, when we point a char array to a pointer, we pass the base address of the array to the pointer. The pointer variable can be dereferenced using the asterisk * symbol in C to get the character stored in the address. For example,

In this case, ptr points to the starting character in the array arr i.e. H. To get the value of the first character, we can use the * symbol, so the value of *ptr will be H. Similarly, to get the value of ith character, we can add i to the pointer ptr and dereference its value to get ith character, as shown below.

Instead of incrementing the pointer manually to get the value of the string, we can use a simple fact that our string terminates with a null \0 character and use a while loop to increment the pointer value and print each character till our pointer points to a null character.

Let us understand this with an example.

hello-world-string-example

Output:

In the above example, we have created a character pointer to a string in C that points to the first address of the array str. To print the value stored in the array, we create a while loop until the value at the location pointed by ptr is not null, which indicates that we have not reached the end of the string. After printing the current character, we increment the ptr pointer to move to the following location. The loop terminates when we reach the null character indicating the end of the string.

Using a Pointer to Store String

Arrays are essentially continuous blocks in the memory; we can also store our strings using pointers and can dereference the pointer variables to access the value of the string. To store the string in a pointer variable, we need to create a char type variable and use the asterisk * operator to tell the compiler the variable is a pointer. This can be understood from the example,

Asterisk operator * can be used to access the ith character of the string that is the value of ith string character will be *(str + i).

Let us understand this with the example where we are using the pointer variable strPtr to store the string value.

example-7-string

Output:

Here, we are using a temporary variable temp, to print the characters of the string because we don't want to lose the starting position of our string by incrementing the pointer strPtr inside the loop.

So at the end of the code, the pointer temp will point to the last character in the string " HelloWorld\0" that is null (\0) but our main pointer strPtr still points to the location of the first character in the string.

Array of Strings

We can use a two-dimensional array to store multiple strings, as shown below. Here, the compiler adds a null character at the end of every string if not mentioned explicitly. The strings can have variable sizes, as shown, but the size of the largest string must be less than (or equal to inclusive of null character) the column size of the 2-D array.

array-of-strings

For 2-D arrays, both the dimensions of the array need to be defined at the time of variable declaration, and our strings don't have to be of the same length. From the figure, we can see each string in the array has addresses that are not utilised that are cells marked with cells filled with red color.

To solve the problem of memory wastage, we can use pointers of size four that can be used to store strings of variable size. In this case, each string takes the memory equal to the string length (inclusive of the null character), preventing memory wastage like in the case of a 2-D array. Here, str[i] represents the base address of the ith string.

This array will be arranged in the memory in the following way,

memory-table

Here, in this example, we have used a 2D char array or a pointer array (char *str[]) to store four where str[0] stores the word "String", str[1] stores "Topics" and so on. Notice how we also store a null character \0 in the memory after the end of each word to identify string termination. Coming to the explanation of locations, str is an array of pointers that has some address in the memory, and the value of the first string "String" is stored in it as a value at the index 0. We can read the value by dereferencing the pointer till we encounter a null character for each string.

example-10-string

In this case, we are using a pointer variable str of size four, because of which we are only allocating space equal to the length of the individual string, this can be visualized from the pictorial representation of the variable str.

To print the strings in the array, we can use the logic shown in the following example.

Output:

In the above example, we use char type pointer variable str of size 4 to store four strings with variable sizes. Unlike a 2-D array, we don't have to define the column size at the time of variable declaration, which saves us unnecessary wastage of memory. str[i] stored the starting address of ith string in the array. Subsequent characters of the string can be evaluated by incrementing on the base address i.e. str[i] + j has the address of jth character of ith string. To get the value of ith string, we increment base address of ith string str[i] till we encounter a null character (indicating string termination) using a while loop.

C program for Pointers with Strings

Now that we have understood how pointers can be used to point to strings in C. Let us see an example where we will take the input string from the user and store it in the character array. Because we have been taking more than one string from the user, the strings will be stored in a 2-D array with the number of rows equal to the number of strings we wish to store. After this, we will iterate on each string using pointers to calculate their sizes and output them on the screen.

Output

Here, we are using a two-dimensional array of subjects that can store five different strings with a maximum length of 20. To take input from the user %s format specifier is used that takes input characters till a new line or a space is detected. To show the strings to the user, we have used the while loop on the inputs till a null \0 is encountered. At the end of the iteration for each string, pointer j indicates the length of each row.

Conclusion

  • String is a data type that stores the sequence of characters in an array. Every string terminates with a null character (\0), indicating its termination.
  • A pointer to a string in C can be used to point to the base address of the string array, and its value can be dereferenced to get the value of the string.
  • To get the value of the string array is iterated using a while loop until a null character is encountered.
  • Instead of using arrays, we can use character pointers to store a string value.
  • To store multiple strings, we can use a 2D array or a pointer variable. Using a 2D array leads to memory wastage because the size of the columns is fixed for every row in a 2D array in C. This can be overcome using pointers.

See Also: