C Pointers and Arrays

1. Array Name as a Pointer

  • In C, the name of an array is treated as a pointer to its first element.

  • That means:



 

  • numbers → address of the first element (numbers[0])


2. Accessing Array Elements Using Pointers

Using pointer arithmetic

 

Output:

Element 0 = 10
Element 1 = 20
Element 2 = 30
Element 3 = 40
Element 4 = 50

*(ptr + i) accesses the i-th element by moving the pointer.


Equivalent Using Array Index



 

  • numbers[i] is the same as *(numbers + i) in C.


3. Modifying Array Elements Using Pointers


 

Output:

2 4 6 8 10

4. Array of Pointers

  • You can also have an array of pointers, each pointing to a variable or string.


 

Output:

Name 1: Alice
Name 2: Bob
Name 3: Charlie

Useful for storing multiple strings efficiently.


5. 2D Arrays and Pointers

  • A 2D array can be accessed using pointers:


 

Output:

1 2 3
4 5 6

6. Key Points About Pointers and Arrays

  1. Array name = pointer to first element.

  2. Access elements with pointer arithmetic: *(ptr + i) = array[i].

  3. Pointers can modify array elements directly.

  4. Array of pointers can store multiple strings efficiently.

  5. For 2D arrays, pointer-to-array syntax: int (*ptr)[cols].

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *