Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

d language
pointer

What are pointers in D?

Mohe Ud Din Sheikh

Overview

In D programming language, a pointer is a variable that points to the memory address of another variable. It can be defined in any datatype like int, char, double, and so on. However, the pointer and the variable whose address is assigned to the pointer should have the same data type. For example, if the pointer is of int data type, then the variable x should also have int data type.

Syntax

Let's look at the syntax:

Initialization

int *p;
Initialization of pointer
  • To initialize a pointer variable, we use an asterisk * with the variable.

Operators

  • Dereferencing operator: To use the dereferencing operator, we again use an asterisk *, and it will help to access the value stored on the address that the pointer points to.
  • Address operator: To use the address operator we use an ampersand & to get the address of that variable.

Code example

Let's look at the code below:

import std.stdio; 

void main () { 
   int a= 10; //Declaring variable a
   int b= 15; //Declaring variable a
   int *p;    //Declaring pointer variable       
   p = &a;    //Storing address of a variable in the pointer 
   p = &b;    //Storing address of b variable in the pointer 
   
   // Address of a variable
   writeln("Address of a: ",&a); 
   
   // Address of b variable 
   writeln("Address of b: ",&b); 
   
   // Address stored in pointer variable 
   writeln("Pointer point's toward address: ",*p); 
}
Example of pointer in D language

Code explanation

  • Line 6: We initialize a pointer variable int *p with the name p by using * before the name of the variable.
  • Line 7: We assign the address of the variable a to the pointer variable p.
  • Line 8: We assign the address of the variable b to the pointer variable p.
  • Lines 10 and 12: We show the address of a and b variables.
  • Line 14: We show the value of the address stored in the pointer by using the dereferencing operator.

RELATED TAGS

d language
pointer

CONTRIBUTOR

Mohe Ud Din Sheikh
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring