Difference between Arrays and Pointers in C

1. Introduction

In C programming, arrays and pointers are fundamental concepts often used interchangeably, but they have different properties and behaviors. An array is a collection of elements of the same type stored in contiguous memory locations. A pointer, on the other hand, is a variable that stores the address of another variable.

2. Key Points

1. Arrays allocate memory blocks to store multiple elements of the same type.

2. Pointers are variables that store memory addresses of other variables.

3. The name of an array represents the address of the first element, similar to a pointer.

4. Pointers can be incremented or decremented, which is not directly possible with arrays.

3. Differences

Arrays Pointers
Fixed size, defined at compile time. Dynamic, can point to any memory address.
Represents a block of memory. Stores the address of a memory location.
Cannot be reassigned to point to another memory block. Can be reassigned to point to different variables.

4. Example

#include <stdio.h>

int main() {
    // Array example
    int arr[3] = {10, 20, 30};
    printf("Array first element: %d\n", arr[0]);

    // Pointer example
    int val = 50;
    int *ptr = &val;
    printf("Pointer points to: %d\n", *ptr);

    return 0;
}

Output:

Array first element: 10
Pointer points to: 50

Explanation:

1. In the array example, arr is an array of integers. arr[0] accesses the first element of the array.

2. In the pointer example, ptr is a pointer that holds the address of val. *ptr is used to access the value pointed to by ptr.

5. When to use?

- Use arrays when you need a collection of similar elements and the size is known or fixed.

- Use pointers for more complex data manipulations, dynamic memory allocation, or when you need to reference different variables during runtime.

Difference between malloc() and calloc()?

Difference between Local Variable and Global Variable in C

Difference between Global and Static Variables in C

Difference Between Call by Value and Call by Reference in C

Difference Between getch() and getche() in C

Difference between printf() and sprintf() in C

Difference between Arrays and Pointers in C

Difference between Structure and Union in C

Difference Between Stack and Heap Memory Allocation in C

Difference Between Macro and Function in C

Difference between = and == in C

Difference Between for loop and while loop in C

Difference Between Linked List and Array in C

Difference between fgets() and gets() in C

Difference between ++i and i++ in C

Difference between struct and typedef struct in C

Difference between int main() and void main() in C

Difference between Character Array and String in C

Difference between break and continue in C

Difference between exit() and return in C

Comments