Pointers with strings in C Language
Categories: C language
We have used pointers with the array, functions, and primitive data types so far. However, pointers can be used to point to the strings. There are various advantages of using pointers to point strings. Let us consider the following example to access the string via the pointer.
#include<stdio.h>
void main ()
{
char s[11] = "javatpoint";
char *p = s; // pointer p is pointing to string s.
printf("%s",p); // the string javatpoint is printed if we print p.
}
Output
javatpoint
As we know that string is an array of characters, the pointers can be used in the same way they were used with arrays. In the above example, p is declared as a pointer to the array of characters s. P affects similar to s since s is the base address of the string and treated as a pointer internally. However, we can not change the content of s or copy the content of s into another string directly. For this purpose, we need to use the pointers to store the strings. In the following example, we have shown the use of pointers to copy the content of a string into another.
#include<stdio.h>
void main ()
{
char *p = "hello javatpoint";
printf("String p: %s\n",p);
char *q;
printf("copying the content of p into q...\n");
q = p;
printf("String q: %s\n",q);
}
Output
String p: hello javatpoint
copying the content of p into q...
String q: hello javatpoint