Posts

Showing posts with the label pointers

CPP Crash Course: SimpleUniquePointers and Move Semantics without memory leakage.

Image
Demonstration of Listing 6-15 and its valgrind output showing how to properly incorporate Move Semantics with Simple Unique Pointers. Github:  https://github.com/pereiradaniel/CPP_CRASH_COURSE/blob/master/P1C6/EXAMPLES/listing_6_15.cpp

C: Constant pointers and pointer to a constant.

  https://github.com/pereiradaniel/c_programs/blob/master/consts_ptrs.c // Illustrate the differences between constant ptr and ptr to a constant #include <stdio.h> int main(int argc, char* argv[]) { char a = 'a'; char b = 'b'; char*const const_ptr = &a; // constant pointer // can't change what it points to // can change the value *const_ptr = 'x'; printf("a: %c\n", a); char const *ptr_to_const = &a; // pointer to constant printf("*ptr_to_const: %c\n", *ptr_to_const); // dereference ptr ptr_to_const = &b; printf("*ptr_to_const: %c\n", *ptr_to_const); // dereference ptr const char *const const_ptr_to_const = &a; // can't dereference this pointer because it is a pointer to a constant! // can't change what the pointer points to! return 0; }

C: Simple Swap Function Using Pointers

https://github.com/pereiradaniel/c_programs/blob/master/pointers2.c #include <stdio.h> // Pass by reference swap function void swap(int *a, int*b) { printf("a: %p\nb: %p\n", a, b); printf("*a: %d\n*b: %d\n", *a, *b); int temp = 0; temp = *a; *a = *b; *b = temp; } int main(int argc, char* argv[]) { // int a,b,c; // a=b=c=0; // printf("Enter 3 numbers: "); // scanf("%d %d %d", &a, &b, &c); // pass by reference // printf("Result: %d\n", a+b+c); int x, y; x = 5; y = 10; printf("x: %d, y: %d.\n", x, y); printf("&x: %p\n&y: %p\n", &x, &y); swap(&x,&y); printf("swap! x: %d, y: %d.\n", x, y); return 0; }

C: Pointers and Dynamic Allocation

https://github.com/pereiradaniel/c_programs/blob/master/pointers3.c   #include <stdio.h> #include <stdlib.h> // malloc int main() { int *a; // declare a pointer to a dynamically allocated array int length = 0; printf("Enter a length: "); scanf("%d", &length); // allocate space dynamically a = malloc(length * sizeof(int)); // allocates space on the heap printf("a: %p\n", a); for (int i=0; i<length; ++i) a[i] = i; for (int i=0; i<length; ++i) printf("a[%d]=%d\n", i, a[i]); free(a); // deallocate memory return 0; } // ==320== Memcheck, a memory error detector // ==320== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al. // ==320== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info // ==320== Command: ./a.out // ==320== // Enter a length: 5 // a: 0x4a4e8c0 // a[0]=0 // a[1]=1 // a[2]=2 // a[3]=3 // a[4]=4 // ==320== // =...