Skip to main content

Pointers And Strings in C

Pointers And Strings

  • A string is simply an array of characters terminated by a null character \0.

  • Pointers are often used to manipulate strings in C, since strings are essentially just arrays of characters and pointers are used to manipulate arrays.

Example 1

#include <stdio.h>

int main()
{
char str1[] = "hello";
char *str2 = "world";

// Print the strings using array notation
printf("str1: %s\n", str1);
printf("str2: %s\n", str2);

// Print the strings using pointer notation
printf("str1: %s\n", &str1[0]);
printf("str2: %s\n", str2);

// Modify the strings using pointers
str1[0] = 'H';
*(str2 + 1) = 'u';

// Print the modified strings
printf("str1: %s\n", str1);
printf("str2: %s\n", str2);

return 0;
}
Output:

Explanation

  • We declare two strings: str1 as an array of characters, and str2 as a pointer to a string literal.
  • We then use both array notation and pointer notation to print out the contents of the strings.
  • Note that when using pointer notation, we can simply pass the pointer to the printf() function instead of passing the address of the first character in the array.
  • Next, we use pointers to modify the first character of each string.
  • Note that we can use either array notation or pointer notation to modify the strings.

Finally, we print out the modified strings using printf().

Example 2

#include <stdio.h>

int main()
{
char str[] = "Hello, world!";
char *ptr = str; // ptr points to the first character in str

// Print the string using pointer notation
while (*ptr != '\0')
{
printf("%c", *ptr);
ptr++; // move to the next character
}
printf("\n");

// Modify the string using pointers
ptr = str;
*ptr = 'h'; // change the first character to 'h'
while (*ptr != '\0')
{
if (*ptr == 'o')
{
*ptr = '0'; // change 'o' to '0'
}
ptr++; // move to the next character
}

// Print the modified string using array notation
printf("%s\n", str);

return 0;
}
Output:

Explanation

  • We declare a string str and a pointer ptr that initially points to the first character in str.
  • We then use the while loop and pointer notation to print out each character in the string, and move the pointer to the next character.
  • Next, we use pointers to modify the string: we change the first character to lowercase, and replace any occurrences of the letter 'o' with the digit '0'.
  • We use the while loop and pointer notation again to traverse the string and modify each character.
  • Finally, we print out the modified string using array notation.