Skip to main content

Posts

Showing posts with the label pointers

Smart pointers in C++

Using pointers in a program increases the risk of memory and resource leaks. Programmers have to make sure that they always free memory (acquired by new operator) using delete operator. Bare pointers in C++ are not exception safe , they do not get destroyed (release memory) if there is an exception in your program. Smart pointers are helpful to avoid all the problems mentioned above. There are many kinds of smart pointers but in this blog post we will discuss 2 types of smart pointers: unique_ptr and  shared_ptr. What are smart pointers ? Smart pointers are wrapper over a normal C++ pointer. They are objects that store pointer to dynamically allocated objects. They conceptually own the object pointed to, they delete the object as soon as object is no longer required and goes out of scope. Difference between normal and smart pointer The main difference between a normal and smart pointer is that normal pointer do not get deleted unless delete operator is called. On other h...

Understanding pointers in C Part1 - Basics of Pointer

Pointers are one of the most difficult concepts in C language to grasp. Many programmers get confused in pointers.I am one of them. I decided to write series of blog posts covering basic to advance concepts of pointers. This is the first part to understand very basic of pointer that what pointer actually is and how we can store/access data through pointers. Put simply A pointer is a variable that contains the address of a variable Lets try to understand pointers using some code. int x=3; int *ptrToX; ptrToX=&x;  In above code we simply took a variable x of type int . Then we define a pointer ( * denotes that variable is a pointer and it is known as indirection or dereferencing operator ) ptrToX  of type int and assigned address of x to ptrToX . Now ptrToX points to x . Note that ptrToX do not contain value of x ( i.e 3 ) instead it contains memory address of x . Now we can access and manipulate value of x using ptrToX . Accessing value of a variable ...