Pointer’s Basic In C / C++

GrowthLadder Article Pointer in C/C++

 

In C, the pointer is a special type of variable that has the special power to store the address of other variables of the same kind (datatype). Like an integer pointer can store the address of another integer variable, or the float pointer can store another float Variables address. The size of the pointer depends on the architecture of the CPU. However, in 32-bit architecture, the size of a pointer is 2 bytes. In language C, we use ‘*’ to declare a pointer.

int *p; // where p is an integer type of pointer

To understand the pointer clearly, first, we have to understand how in memory the variables are allocated in language C.

When we declare a variable in any programme then one memory address is located against that variable and the size of the memory will be according to the data type of that variable, then the starting address of that memory allocated to the particular variable is returned to the programme/compiler. And the programme/compiler makes a note of that in a symbol table. When we assign some value against that variable then, The value is stored in that particular memory location using the memory address we have for the variable. Now in that particular programme, all the times we display or use the value of that variable we use to refer to the same memory location every time. So “Pointer is such a type of variable which can hold these type of memory address for another variable”.

Now to understand it in a better way we can take an example, suppose in a small village one of your friends lives. Suppose his name is Amit. Now we can identify his house by Amit’s house. In the village, everyone knows other’s houses by their name. So if we want to send anything to his house we can just send it by mentioning his name. This is like in a program you declare a variable & then use that variable by its name. Now like every house Amit’s house also has a proper address. So we can also send something to his house by maintaining the proper address rather than his name. This is the case of the ‘Pointer’ in C. With a pointer, we refer to a variable not by its name but by its memory address. And as the address is stored in a special type of variable we called that variable type a pointer.

GrowthLadder Article Pointer in C/C++

In the above picture, we have 4 lines of code, and there “i” is an integer type of variable whose starting memory address is 1894637, now we have declared another variable whose type is an integer pointer. Then we store the starting memory address of “i” to “p” by the ampersand “&” operator. Now it is the same it we write i=200 or *p=200 as “*p” is pointing to “i” now.

Whenever a C program is executed some memory is allocated in the RAM for the program execution. This memory is used for storing the frequently executed code (binary data), program variables, etc.

Typically there are three types of variables:

○ Local variables (also called automatic variables in C)
○ Global variables
○ Static variables
○ You can have global static or local static variables, but the above three are the parent types.

5 Memory Segments in C:

1. Code Segment :

• The code segment, also referred as the text segment, is the area of memory that contains the frequently executed code.
• The code segment is often read-only to avoid risk of getting overridden by programming bugs like buffer-overflow, etc.
• The code segment does not contain program variables like local variables (also called as automatic variables in C), global variables, etc.
• Based on the C implementation, the code segment can also contain read-only string literals. For example, when you do printf(“Hello, world”) then string “Hello, world” gets created in the code/text segment. You can verify this using size command in Linux OS.

2. Data Segment :

The data segment is divided in the below two parts and typically lies below the heap area or in some implementations above the stack, but the data segment never lies between the heap and stack area.

Uninitialized data segment :

• This segment is also known as bss.
• This is the portion of memory that contains:

1. Uninitialized global variables (including pointer variables)
2. Uninitialized constant global variables.
3. Uninitialized local static variables.

• Any global or static local variable which is not initialized will be stored in the uninitialized data segment
• For example global variable int globalVar; or static local variable static int localStatic; will be stored in the uninitialized data segment.
• If you declare a global variable and initialize it as 0 or NULL then still it would go to an uninitialized data segment or bss.

Initialized data segment :

• This segment stores:

1. Initialized global variables (including pointer variables)
2. Initialized constant global variables.
3. Initialized local static variables.

• For example: global variable int globalVar = 1; or static local variable static int localStatic = 1; will be stored in initialized data segment.
• This segment can be further classified into initialized read-only area and initialized read-write area. Initialized constant global variables will go in the initialized read-only area while variables whose values can be modified at runtime will go in the initialized read-write area.
The size of this segment is determined by the size of the values in the program’s source code, and does not change at run time.

Stack Segment :

• Stack segment is used to store variables which are created inside functions (function could be a main function or user-defined function), variables like

1. Local variables of the function (including pointer variables)
2. Arguments passed to function
3. Return address

• Variables stored in the stack will be removed as soon as the function execution finishes.

Heap Segment :

• This segment is to support dynamic memory allocation. If the programmer wants to allocate some memory dynamically then in C it is done using the malloc, calloc, or realloc methods.
• For example, when int* prt = malloc(sizeof(int) * 2) then eight bytes will be allocated in heap and memory address of that location will be returned and stored in ptr variable. The ptr variable will be on either the stack or data segment depending on the way it is declared/used.

Pointers are a powerful feature in C programming, allowing developers to directly access memory locations and manipulate data more efficiently. In this article, we will provide an in-depth understanding of Pointers in C, their types, and how to use them effectively in various scenarios.

A pointer is a special variable that stores the address of another variable. Pointers in C are widely used for various purposes, such as accessing memory locations, creating dynamic data structures, and optimizing code execution time. They are denoted by an asterisk (*) symbol and declared with a specific data type.

int *pointer_variable;

Here, int *pointer_variable declares a pointer named pointer_variable of type int. The pointer will store the address of an integer variable.

Address in C : 

Every variable in a C program has an associated memory address. This address can be retrieved using the ampersand (&) operator placed before the variable name. For example:

int var;
printf("Address of var: %p", &var);

In this example, &var returns the memory address of the integer variable var. The %p format specifier is used in the printf function to display the address in a hexadecimal format.

Declaring and Initializing Pointers :

Declaration

A pointer must be declared before it can be used in a program. The declaration syntax is as follows:

data_type *pointer_variable_name;

Here, data_type represents the type of variable the pointer will point to, and pointer_variable_name is the name of the pointer variable.

Initialization

After declaring a pointer, it should be initialized with the address of a variable. Uninitialized pointers may lead to unpredictable results and potential errors. To assign the address of a variable to a pointer, use the following syntax:

pointer_variable = &variable;

For example:

int var = 5;
int *ptr;
ptr = &var;

Here, the address of the integer variable var is assigned to the pointer ptr.

Types of Pointers : 

There are several types of pointers in C, each with its specific use cases and characteristics.

Null Pointer

A null pointer is a pointer that is initialized with a null value (0). It represents an empty or invalid memory location. Initializing a pointer with a null value is useful when you don’t have any specific address to assign at the time of declaration.

int *ptr = NULL;

Void Pointer

A void pointer, also known as a generic pointer, is a pointer that doesn’t have a specific data type. It is declared using the void keyword and can be used to store the address of any type of variable. To access the value stored in a void pointer, it must be typecast to the appropriate data type.

void *ptr;

Wild Pointer

A wild pointer is a pointer that has been declared but not initialized with any address. Wild pointers can be dangerous, as they may point to unknown or unintended memory locations, leading to segmentation faults or other errors.

int *ptr;

Dangling Pointer

A dangling pointer is a pointer that points to a memory location that has been deallocated. Dangling pointers can cause memory corruption, as they may still be used to access or modify the deallocated memory.

int *ptr = (int *)malloc(sizeof(int));
free(ptr);

In this example, after the memory allocated to ptr is freed, ptr becomes a dangling pointer.


Pointer Arithmetic : 

Pointer arithmetic allows developers to perform arithmetic operations on pointers, such as incrementing or decrementing the pointer’s value to access memory locations more efficiently. Some common pointer arithmetic operations include:

Increment and Decrement

Pointers can be incremented or decremented to move to the next or previous memory location, respectively.

ptr++; // Increment pointer
ptr--; // Decrement pointer

Addition and Subtraction

Adding or subtracting an integer value from a pointer will move the pointer by a specific number of memory locations.

ptr += n; // Move pointer n positions forward
ptr -= n; // Move pointer n positions backward

 

**So these are the basic concepts of “Pointers”. Next, we shall discuss the relations between Arrays & Pointers in a separate article.**

You May Also Like…

Single Linked List in C

Single Linked List in C

  Single Linked List is a fundamental data structure in the C programming language. It allows us to store and...

0 Comments