Get to know C Pointer

Address vs value

Each variable has two attributes: address and value. The address is the location in memory. In that location, the value is stored.

During the lifetime of the variable, the address is not changed but the value may change.

Pointer

A pointer is a variable whose value is an address. A pointer to an integer is a variable that can store the address of that integer.

Pointers are used manipulate the computer's memory.

Syntax

Pointer variables are declared by using the asterisk(*).

The following line declares an integer pointer, s:

int *s;

The ampersand & is used to get the address.

Example

The following code shows how to use define int pointer variable.

int *p, q defines two variables. One is q which is a normal int type variable. *p is an int point variable. *p represents the int value while p itself is the address of *p.

q = 19; just assigns value 19 to q, which is a normal int type variable.

p = &q; is interest. It uses the & operator to get the address q and assign the address to p. Now p points to q.

In printf("%d", *p);, *p gets the value of of p and printf outputs the value to console.


#include <stdio.h>
//w  ww. ja  v a2s . c o  m
int main(void)
{
  int *p, q;

  q = 19; /* assign q 19 */

  p = &q; /* assign p the address of q */

  printf("%d", *p); /* display q's value using pointer */

  return 0;
}




















Home »
  C Language »
    Language Advanced »




File
Function definition
String
Pointer
Structure
Preprocessing