Back to: C Tutorials For Beginners and Professionals
Character Pointer in C Language with Examples
In this article, I am going to discuss Character Pointer in C Language with Examples. Please read our previous articles, where we discussed Passing Pointer to Function in C Language with Examples. At the end of this article, you will understand what is Character Pointer and why we need Character Pointers, and how to create Character Pointers in C Language.
Character Pointer in C Language:
A pointer may be a special memory location that’s capable of holding the address of another memory cell. So a personality pointer may be a pointer that will point to any location holding character only. Character array is employed to store characters in Contiguous Memory Location. char * and char [] both are wont to access character array, Though functionally both are the same, they’re syntactically different. Since the content of any pointer is an address, the size of all kinds of pointers ( character, int, float, double) is 4.
char arr[] = “Hello World”; // Array Version
char ptr* = “Hello World”; // Pointer Version
Example:
#include<stdio.h> #include<string.h> int main () { char str[10]; char *ptr; printf ("enter a character:\n"); gets (str); puts (str); ptr = str; printf ("name = %c", *ptr); }
Output:
Example for better understanding:
#include<stdio.h> #include<stdlib.h> int main () { int n, i; char *ptr; printf ("Enter number of characters to store: "); scanf ("%d", &n); ptr = (char *) malloc (n * sizeof (char)); for (i = 0; i < n; i++) { printf ("Enter ptr[%d]: ", i); /* notice the space preceding %c is necessary to read all whitespace in the input buffer */ scanf (" %c", ptr + i); } printf ("\nPrinting elements of 1-D array: \n\n"); for (i = 0; i < n; i++) { printf ("%c ", ptr[i]); } //signal to operating system program ran fine return 0; }
Output:
In the next article, I am going to discuss Pointer to Constant in C Language with Examples. Here, in this article, I try to explain Character Pointer in C Language with Examples. I hope you enjoy this article. I would like to have your feedback. Please post your feedback, question, or comments about this article.