String using pointers

Home / C Programming / String using pointers

String using pointers


In C, strings are represented as arrays of characters, terminated by a null character `'\0'`. Pointers are commonly used to work with strings because they allow easy manipulation and traversal of characters in the string.

Here's how you can work with strings using pointers in C:

1. Initializing a string:

You can initialize a string using an array of characters. Since arrays decay into pointers when used with strings, you can also use a pointer to initialize a string.

char str1[] = "Hello, world!"; // Using an array

char *str2 = "Hello, world!";  // Using a pointer

2. Accessing characters in the string:

You can use pointer arithmetic to traverse through the string and access individual characters.


// Output: Hello, world!

3. String functions using pointers:

C standard library provides various string functions that work with pointers. Some common ones are:

- `strlen`: Calculates the length of the string.

- `strcpy`: Copies one string to another.

- `strcat`: Concatenates two strings.

- `strcmp`: Compares two strings.

Here's an example of using `strlen` and `strcpy`:


4. Dynamic allocation of strings:

You can dynamically allocate memory for strings using `malloc` (or `calloc`) and then work with them using pointers.


Remember to allocate enough memory to accommodate the string and the null terminator, and always free the memory when you're done using it to avoid memory leaks.

Working with strings using pointers in C gives you more flexibility in handling and modifying strings, but it also requires caution to avoid accessing memory outside the allocated boundaries and causing undefined behavior.