difference between array and pointer

Difference between Array and Pointer

Introduction

Array and pointer are two important concepts in computer programming. Both are used to store and manipulate data, but they are different from each other in many ways. In this article, we will explore the differences between array and pointer.

Definition

An array is a collection of similar elements that are stored in contiguous memory locations. Each element in the array is accessed by an index number, starting from 0.

A pointer is a variable that stores the memory address of another variable. It points to the location of the variable in memory.

Memory Allocation

Arrays are allocated a fixed amount of memory at compile time. The size of the array is determined when the array is declared. The memory for the array is allocated in contiguous blocks.

Pointers, on the other hand, are allocated memory at run time. The memory for pointers is allocated dynamically using functions such as malloc and calloc.

See also  difference between direct debit or standing order

Usage

Arrays are used to store a fixed number of elements of a specific type. They are often used for data structures such as lists, queues, and stacks.

Pointers are used to store memory addresses of variables. They are used for dynamic memory allocation, passing parameters to functions, and implementing data structures such as linked lists, trees, and graphs.

Accessing Elements

In arrays, elements can be accessed using the index number. For example, arr[0] would access the first element of the array.

In pointers, the value of the pointer is the memory address of the variable it points to. To access the value of the variable, we need to use the indirection operator (*). For example, *ptr would access the value of the variable pointed to by ptr.

Conclusion

In conclusion, arrays and pointers are two important concepts in computer programming. They serve different purposes and are used in different situations. Arrays are used to store fixed amounts of data, while pointers are used to store memory addresses of variables. Understanding the differences between array and pointer is important for writing efficient and effective code.

See also  Know the Structure of Animal Cells and Their Functions and Characteristics

Table difference between array and pointer

Array Pointer
Represents a fixed-size collection of similar data types. Represents a variable that holds the memory address of a value or object.
Uses the index to access elements sequentially. Uses the pointer arithmetic to access elements of an array or dynamic memory allocation.
Cannot be reassigned to another memory block. Can be reassigned to different memory locations.
Has a fixed size, determined at compile-time. Can have a dynamic size, determined at run-time.
The name of an array itself is a constant pointer to the first element. Pointer variables must be explicitly dereferenced to access the value pointed to.