
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Explain the Concepts of Pointers and Arrays in C Language
Pointers and Arrays
A pointer in C is a variable that stores the address of another variable, which can be of any type(char, int, function). In a 32-bit system, the size of the pointer is 2 bytes.
An array is a collection of similar data items stored in contiguous memory locations. In C, arrays can store various data types(char, int, double float) as well as specific types(pointer structures). For example, if we need to represent an array of 5 elements we need to create it as -
int a [5] = {10, 20,30,40,50};
These five elements are stored as follows ?
If ?p' is declared as an integer pointer, then the array ?a' can be pointed by the following assignment ?
p=a; or p=&a[0];
Each value of ?a' is accessed by using p++ to move from one element to the next. When a pointer is incremented, its value increases by the size of the datatype it points to. This length is called the "scale factor". The relationship between pointer p and variable a is shown below ?
P = &a[0] = 1000; P+1 = &a[1] = 1004; P+2 = &a[2] = 1008; P+3 = &a[3] = 1012; P+4 = &a[4] = 1016;
The address of an element is calculated using its index and the scale factor of the datatype. The address of a[3]=base address+(3*scale factor of int) is calculated as -
=1000+(3*4) =1000+12 =1012
Example
The following C program reads 5 integers into an array and then uses a pointer to print each element. This specifies pointer arithmetic, array input, and output in a structured manner.
#include <stdio.h> int main() { int a[5]; int *p, i; printf("Enter 5 elements: "); for (i = 0; i < 5; i++) { scanf("%d", &a[i]); } p = a; printf("Elements of the array are: "); for (i = 0; i < 5; i++) { printf("%d ", *(p + i)); } return 0; }
Output
The result is obtained as follows ?
Enter 5 elements : 10 20 30 40 50 Elements of the array are : 10 20 30 40 50