C Program to Print Elements of Array using Pointers
The following program to Print Elements of Array using Pointers with simple code with examples.
The C pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to store any variable address. The general form of a pointer variable declaration as follow.
type *var-name;
Here, type is the pointer’s base type; it must be a valid C data type and var-name is the name of the pointer variable. The asterisk * used to declare a pointer is the same asterisk used for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer.
Every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator, which denotes an address in memory.
- We define a pointer variable, int *p
- to assign the address of a variable to a pointer p=&x, x is an integer variable
- Finally access the value at the address available in the pointer variable. v=*p
Save program in a file, Compile program, debug errors,
Execute or Run program with necessary inputs. Verify the outputs obtained.
How it works?
Step1: start
Step2: Read array a[] with n elements
Step 3: initialize pointer p=&a[0] [or p=a]
Step 4: if i<n go to next step otherwise go to step 7
Step 5: print *(p+i)
Step 6: i=i+1 go to step 4
Step 7: stop
Example: C Program to Print Elements of Array using Pointers
Program to print the elements of array using pointers* #include<stdio.h> main() { int a[5]={5,4,6,8,9}; int *p=&a[0]; int i; clrscr(); for(i=0;i<5;i++) printf("%d ",*(p+i)); getch(); }
Output
5 4 6 8 9
Let me know if you find any difficulty in understanding this C Program to Print Elements of Array using Pointers example and I would be glad to explain it further.