pointer in c

Define Pointer

1
int* ptr;

This declares ptr as a pointer to int

Operators

  • * Operator
    1. Means “Pointer” when assignment and initialization.
    2. Means “Go To” the address it stored.
  • & Operator
    Means “Get Address”.

Usage:

  1. Initialization
1
2
int i=10;
int* ptr = &i;
  1. Assignment
1
2
3
int i = 10;
int *ptr;
ptr = &i;

List Pointer

Let’s take this as an example.
Notice that type of tha array must match that of the pointer.

1
2
int a[10];
int *ptr;

Assign the address of a[0] to pointer ptr.

1
ptr = &a[0];

In C, this could be replaced by:

1
ptr = a;

Also, because elements in an array are continuous:

1
*(ptr+i) == a[i] == *(a+1) 

Remind that a could not change, but ptr could change.

String Pointer

Malloc Function.