C program to Create, Initialize and Access a Pointer variable
In this C Programming example, we will implement the program to create, initialize and access a pointer variable and print the output on the console.
1. Create, initialize and access a pointer variable
Like variables, the “Pointer Variable” in C programming has to be declared before they can be used in the program. They can be named after anything as long as they abide by the C Programming rule structure.
A Pointer declaration has the following form
data_type * pointer_variable_name;
After declaring a pointer, we have to initialize it like standard variables with a variable address.
The syntax of initializing pointer variable is
char ch; char *ptrCh; ptrCh = &ch;
Helpful topics to understand this program better are
2. C program to create, initialize and access a pointer variable
Let’s discuss the execution(kind of pseudocode) for the program to create, initialize and access a pointer variable in C.
- Initially, in the program, we declare a variable
chaand pointer*ptrCha. - After declaring the pointer variable we need to initialize them accordingly.
- Here,
ptrCha = &chawe have initialized the pointer variableptrChawith the address ofchar cha. - Now, we access the value and address of
char chausing the pointer variable and print the output on the console.
Let us now implement the above execution of the program to create, initialize and access a pointer variable in C.
#include <stdio.h>
int main() {
// create char variable
char cha;
// Initialize the pointer to char variable
char *ptrCha;
// Initializing the pointer variable with
// the address of variable cha
ptrCha = &cha;
// Assigning value to the variable cha
cha = 'A';
// access value and address of cha
// using variable cha
printf("The Value of cha: %c\n", cha);
printf("The Address of cha: %p\n", &cha);
// access value and address of cha using
// pointer variable ptrCha
printf("The Value of cha: %c\n", *ptrCha);
printf("The Address of cha: %p", ptrCha);
return 0;
}Output The Value of cha: A The Address of cha: 0060FEFB The Value of cha: A The Address of cha: 0060FEFB
3. Conclusion
In this C Programming example, we have discussed how to create, initialize and access a pointer variable in C.
Helpful Links
Please follow C Programming tutorials or the menu in the sidebar for the complete tutorial series.
Also for the example C programs please refer to C Programming Examples.
All examples are hosted on Github.
Recommended Books
An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding
Do not forget to share and Subscribe.
Happy coding!! ?