Skip to content

Instantly share code, notes, and snippets.

@afsalthaj
Last active March 12, 2019 22:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afsalthaj/1cf8670cdd6e4fdeec7e4462cda5ee02 to your computer and use it in GitHub Desktop.
Save afsalthaj/1cf8670cdd6e4fdeec7e4462cda5ee02 to your computer and use it in GitHub Desktop.
//
// main.c
// Explanation of pointer to pointer by deleting a node from linked list.
//
// Created by Afsal Thaj on 10/3/19.
// Copyright © 2019 Afsal Thaj. All rights reserved.
//
//
// The concept discuss about pointers to pointers: https://www.eskimo.com/~scs/cclass/int/sx8.html
#include <stdio.h>
int main(int argc, const char * argv[]) {
// declaring a variable as 5;
int i = 5;
// delcaring a pointer ip that points to the address of the variable i
int *ip = &i;
// Now let's define a pointer to pointer and try and dereference it.
int **ipp;
// ipp now has the address of the pointer that points to the variable i.
ipp = &ip;
printf("the value when deferencing a pointer %i to pointer should be another address: %i \n.", ipp, *ipp);
printf("the value when dereferencing a pointer to pointer will be: %i\n", **ipp);
struct linkedList
{
int item;
struct linkedList *next;
};
struct linkedList innerList;
struct linkedList innerInnerList;
innerInnerList.item = 3;
struct linkedList ll;
innerList.item = 2;
innerList.next = &innerInnerList;
ll.item = 1;
ll.next = &innerList;
struct linkedList *lp, *previousList;
// Let's delete an element from linked list with the value 1.
// Approach 1
for (lp = &ll; lp != NULL; lp = (*lp).next)
{
if ((*lp).item == 2)
{
if (lp == &ll) {
ll = *(*lp).next;
break;
}
else {
(*previousList).next = (*lp).next;
break;
}
}
previousList = lp;
}
printf("The result list is %i, %i\n", ll.item, *(ll.next));
// Approach 2 - Pointer to Pointer
// Let's define new list
struct linkedList list;
struct linkedList a;
struct linkedList b;
b.item = 3;
a.item = 2;
a.next = &b;
list.item = 1;
list.next = &a;
struct linkedList **lpp;
struct linkedList *lp1 = &list;
for(lpp = &lp1; lpp!=NULL; lpp=&((**lpp).next)) {
if ((**lpp).item == 2) {
*lpp = (**lpp).next;
break;
}
}
// Note that list remain unchanged, and lp1 is the reference to the linked list with the deleted element
printf("The result list is %i, %i\n", (*lp1).item, *((*lp1).next));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment