repl.it
@molinitomario/

Data types, Arrays, Pointers

C++

No description

fork
loading
Files
  • main.cpp
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>

int main() {
  std::cout << "Hello World!\n";
  int numbers[] = {1, 2, 3};
  for(int number : numbers)
  {
    std::cout << number;
  }

  // Pointers
  // - pointers are variables that contain the address of another variable in memory
  // simply put "address of " the variable its equal to
  int *Pointer = NULL;
  int value = 5;
  Pointer = &value;
  // in order to get the value from a variable you are going to have to use te & operator
  //// & - "address of" operator -> gets the address of the current variable
  std::cout << "The location in memory that the pointer is aiming toward: " << Pointer;

  // in order to actually get the value in the address location you have to dereference the pointer, thus resturning back the actual value that was stored in that memory adddress
  int ActualValue = *Pointer;
  // * - "contents of" operator
  std::cout << std::endl;
  std::cout << "The actual value of the pointer: " << ActualValue;

  // Dynamic memory
  // - dynamic memory is used when the user himself allocates / deallocated memory
  // - the memory allocated is stored in the ----->>>> heap
  // - the memory that is not alloacted manually is stored in the ------>>>>> stack

  // to allocate memory for a variable use
  int *Point = NULL;
  Point = new int; // allocated memory necessary for storing an integer on the heap, and returns that address 
  std::cout << std::endl;
  std::cout << "Below we have allocated memory: ";
  std::cout << Point;
  int SomeOtherValue = 6;
  Point = &SomeOtherValue;
  std::cout << std::endl;
  std::cout << "THis is the value of the allocated memory: " << *Point;
  std::cout << std::endl;
  delete Point;
  // you would think that deleting would remove this value from memory, but in fact it does not, we have here what is called "Dangling Pointer". The pointer is never removed from memory, to be more exact it is not removed form the stack. Did you say the stack? Yup, a pointer is strored inside of the stack, and since the delete keyword only dealloates value that are in the heap this resulting in having a pointer that is null.
  std::cout << std::endl;
  Point = new int;
  std::cout << "THis is the value of the Dangling Pointer: " <<  *Point;
  std::cout << Point;



}
Fetching token
?