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.

  1. Initially, in the program, we declare a variable cha and pointer *ptrCha.
  2. After declaring the pointer variable we need to initialize them accordingly.
  3. Here, ptrCha = &cha we have initialized the pointer variable ptrCha with the address of char cha.
  4. Now, we access the value and address of char cha using 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!! 😊

Recommended -

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x