computer-scienceangular-roadmapbackend-roadmapblockchain-roadmapdba-roadmapdeveloper-roadmapdevops-roadmapfrontend-roadmapgo-roadmaphactoberfestjava-roadmapjavascript-roadmapnodejs-roadmappython-roadmapqa-roadmapreact-roadmaproadmapstudy-planvue-roadmapweb3-roadmap
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
41 lines
1.4 KiB
41 lines
1.4 KiB
# Pointers |
|
|
|
A pointer is a variable that stores the memory address of another variable (or function). It points to the location of the variable in memory, and it allows you to access or modify the value indirectly. Here's a general format to declare a pointer: |
|
|
|
```cpp |
|
dataType *pointerName; |
|
``` |
|
|
|
**Initializing a pointer:** |
|
|
|
```cpp |
|
int num = 10; |
|
int *ptr = # // Pointer 'ptr' now points to the memory address of 'num' |
|
``` |
|
|
|
**Accessing value using a pointer:** |
|
|
|
```cpp |
|
int value = *ptr; // Value now contains the value of the variable that 'ptr' points to (i.e., 10) |
|
``` |
|
|
|
## References |
|
|
|
A reference is an alias for an existing variable, meaning it's a different name for the same memory location. Unlike pointers, references cannot be null, and they must be initialized when they are declared. Once a reference is initialized, it cannot be changed to refer to another variable. |
|
|
|
Here's a general format to declare a reference: |
|
|
|
```cpp |
|
dataType &referenceName = existingVariable; |
|
``` |
|
|
|
**Example:** |
|
|
|
```cpp |
|
int num = 10; |
|
int &ref = num; // Reference 'ref' is now an alias of 'num' |
|
``` |
|
|
|
Modifying the value of `ref` will also modify the value of `num` because they share the same memory location. |
|
|
|
**Note:** References are generally used when you want to pass a variable by reference in function arguments or when you want to create an alias for a variable without the need for pointer syntax. |