User Tools

Site Tools


programming:cplusplus:start

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
programming:cplusplus:start [2022/02/28 18:16]
dwheele [Pointers, References]
programming:cplusplus:start [2022/02/28 18:43] (current)
dwheele [Reference]
Line 32: Line 32:
 https://www.youtube.com/watch?v=DTxHyVn0ODg&list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb&index=16 https://www.youtube.com/watch?v=DTxHyVn0ODg&list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb&index=16
  
-A pointer is an integer which stores a memory address.+A pointer is an integer which stores a memory address. Types have nothing to do with that.
  
 +
 +The value 0 is not a valid memory address. It means 0
 +
 +<code c++>
 +int main()
 +{
 +   // void* ptr = 0; // or   void* ptr = nullptr;
 +   int var = 8;
 +   // Where are you in memory
 +   int* ptr = &var; // Get the location of var, and put it into ptr as an integer pointer.
 +   
 +   *ptr = 9; // int value pointed at by pointer "ptr"
 +   
 +   std::cin.get();
 +}
 +</code>
 +
 +<code c++>
 +int main()
 +{
 +   char* buffer = new char[8];// This uses heap
 +   memset(buffer, 0, 8);
 +   
 +   char** ptr = &buffer;// Pointer to a pointer
 +   
 +   delete[] buffer;// delete afterward to be nice
 +   
 +   std::cin.get()
 +}
 +</code>
  
  
 ===== Reference ===== ===== Reference =====
  
 +Pointers and references are about the same thing. How we write them is different. References are syntax sugar on top of a pointer.
 +
 +References reference an existing variable.
 +
 +<code c++>
 +int main()
 +{
 +   int a =5;
 +   int& ref = a;// the & is part of the int defintion
 +   // We have created an alias. It is not really a variable.
 +   // We can use ref as though it is "a"
 +   
 +   ref = 2;
 +   std::cout(ref);
 +}
 +// Works, but this is clumsy
 +
 +void Increment (int* value)
 +{
 +   (*value)++;// Value at the pointer "value"
 +}
 +int main()
 +{
 +   // We want to pass the memory address.
 +   int a = 5;
 +   Increment(&a);
 +   LOG(a);
 +}
 +
 +</code>
 +<code c++>
 +// Use a reference instead of a pointer
 +
 +void Increment(int& value)
 +{
 +   value++;
 +}
 +int main()
 +{
 +   int a = 5;
 +   Increment(a);
 +   LOG(a)
 +}
 +
 +</code>
  
  
programming/cplusplus/start.1646072174.txt.gz ยท Last modified: 2022/02/28 18:16 by dwheele