Site icon TestingDocs.com

C Pointers

Overview

In this tutorial, we will learn about C Pointers. A pointer is a variable that stores memory addresses of other variables. The values that we assign to a pointer are memory addresses of other variables or other pointers.

C pointers are characterized by their value and data type. The value is the address of the memory location the pointer points to, the type determines how the pointer will be incremented/decremented in pointer arithmetic.

Declare Pointer Variable

Pointers are declared by using the asterisk(*). The * operator is called the value at address operator.

int *p;

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.

Example

Let’s understand the concept with a sample C program.

 

/**
**********************************
* Program Description:
* C pointer Demo
* Filename: pointer.c
* C Tutorials - www.TestingDocs.com
*************************************
*/
#include
int main()
{
    int number = 100;//declare integer variable
    int *p;          //pointer variable
    p = &number;     //store number memory address

    printf(" The address of the number is = %u \n", p);
    printf(" The value stored at the memory address is = %d \n", number);
    printf(" The value stored at the memory address is = %d \n", *p);
    printf(" The address of p is = %u \n", &p);
    return 0;
} // end main

Sample Output

The address of the number is = 6356500
The value stored at the memory address is = 100
The value stored at the memory address is = 100
The address of p is = 6356504

We can notice in the program output that the number variable is stored at the memory address 6356500.

The & operator is the Address of the operator in C. The program statement in the example

p = &number;

The &number returns the physical memory address of the variable number. The memory address is stored in the pointer variable p.

The variables used in the C program can be visualized as shown:

The *p expression returns the value stored in the memory address that is stored in the pointer variable p. The *p returns the value of the variable number. This is because the number variable is stored in the physical memory address that is stored in the pointer variable p. We can also get the memory address of the pointer variable with &p expression.

 

C Tutorials

C Tutorials on this website can be found at:

https://www.testingdocs.com/c-language-tutorial/

Exit mobile version