DEV Community

Hieu Nguyen
Hieu Nguyen

Posted on • Edited on • Originally published at devsurvival.com

Learn Pointers in C and C++ In Five Minutes

Alt Text

Ahh the good old pointers. The first topic in most computer science program that most students struggle with. I admit. Not everyone uses pointers in their day to day programming life. In fact, I have never had to use pointers during my internship at several companies. However, after taking operating systems and several critical computer science courses, I realized that they all share one common enemy or ally depending on your perspective: Pointer. Its annoying persistance to show up in my education career has forced me to reconsider its significance and relavance in the developer world.

Although most developers will never have to use it, it is good to know that it exists and the role it serves in your everyday computing life. Heres why. Every application you write will consume memory. That is an undeniable fact that you just have to accept. Anything that touches memory will inherently involve using pointers. Some may argue that even the most complex python program does not include a single pointer. In reality, the python language has taken care of that work for you, so you don't have to. spoiled bastard 😙

What is a pointer?

A pointer is just a generic name given to a variable that holds the memory address of something. The analogy here is that a pointer is the street sign that points *no pun intended, you to the location where you want to go.

Declaring a Pointer

int *int_pointer;
char *char_pointer;
float *float_pointer;
struct Person *person_pointer;

The general format of a pointer is the [Data Type] *[Variable Name]. the * indicates that the variable of that specific data type is a pointer.

Initializing a Pointer

Pointers store memory addresses, but how do we get the memory address of something? C has a special built in operator & that returns the address of any value.

int value =2;
int *location_of_value = &value;

here the variable value contains 2, and we retrieved the location of this "2" in memory using &value and assigned it to the pointer *location_of_value

Retrieve The Value From The Pointer

Given a pointer, to retrieve the value from the pointer, we have to dereference it using *. In other words, once we see the street sign, how do we travel to get to the location?

int value =2;
int *location_of_value = &value;
int retrieved_value=*location_of_value; // retrieved_value == 2

Here we are retrieving the value from the location using *location_of_value

Special Cases of pointers

Arrays

Arrays of any data type is a special case of pointer usage where the variable associated with the array is the pointer to the first element of the array. Sound confusing? So was I.

int arr[3]= {1,2,3};
printf("%p\n", arr);

the %p in the printf statement is used to print the address of pointers. Here when we print the address of the pointer and pass arr, we expect arr to contain an address. what is stored at this address?

int arr[3]= {1,2,3};
printf("%d\n", *arr);// prints 1

when we deference this address stored in arr we get the value 1, which is the first element in the array. To get the next value in the array, we just tell the pointer to move to the next address.

int arr[3]= {1,2,3};
printf("%p\n", arr);// prints 1
arr++;
printf("%d\n", *arr); // prints 2

When we increment the pointer we are telling it to move over by sizeof(int) bytes which is the memory address of the next element in the array.

Strings

There is actually no such things as a string in C. A string is just an array of char.

 char str[10]= "Hi There\0";
 printf("%c", *str); // prints "H"

Here str points to the memory address of the first character in the sequence of char. To print the entire string

char str[10] = "Hi There \0";
while(str){
    printf("%c", *str);
    str++;
}
// prints "Hi There"

Classes and Structs

structs and classes are a little different in their derefencing step

typedef struct person{
    char* first_name;
    int age;

}person;
.
.
.   
char name[10] = "Bob";
person p1 = {name, 21};
person *p1_location = &p1;
printf("First name:%s age:%d \n", p1_location->first_name,(*p1_location).age);

To access the member fields of the person struct given a struct person *, there are two ways.

  1. p1_location->firstname -Dereference and access in one operator
  2. (*p1_location).firstname -Dereference first and then access

Memory Allocation and pointers

Pointers are also used when allocationg block of memories

char *str_ptr = malloc(sizeof(char) * 10)
strcpy(str_ptr, "hello\0");
printf("%s\n", str_ptr) // prints "hello"

Here we are asking malloc to give us a block of memory that can store 10 characters and return to us the starting memory address of the first location.

Final Note

This list of examples is not an exhaustive list of ways that pointers are applied, but it is a good starting point for those who are new to memory addresses and pointers. Peace Out :)

originally post at https://www.devsurvival.com/pointers-with-c/

related posts

Top comments (3)

Collapse
 
codemouse92 profile image
Jason C. McDonald
Collapse
 
htnguy profile image
Hieu Nguyen • Edited

Great Article. Would you like me to link your article at the bottom. Some may need additional resources.

Collapse
 
codemouse92 profile image
Jason C. McDonald

You could if you want, sure. Technically, the post was by someone else; only the top comment was mine.