I am a C++/Java amateur but completely new to C#. My goal is to make a Tree where Nodes are pointers instead of entire objects that are constantly and slowly copied. That way I can simply pass a memory address instead of copying entire objects byte by byte. However, I need to first understand how to use pointers in C#.
- Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object. At Program.$(String[] args) on line 19 [*p1 = 45;]. ---Do pointers have to be tied to objects, not allowed to be static (free roaming)? Does the compiler not know the pointer is pointing to an int?
- Why can I not use Main() here? Does Main() need to be inside a class/be tied to an object?
- How do I know where (inside the code, not the compilation file) to put the unsafe{} block?
- What all needs classes and what all can act as stand-alone code? I understand that code reusability screams "Make this a class!" but how do you make code not be tied to an object (i.e. make static but functional code) in C#?
using System;
//unsafe{} is necessary to use pointers.
//In addition to this block, add the compiler flag "-unsafe" or set the flag to True
//FOR VSCode: Add the following to ProjectName.csproj:
// <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup>
//static void Main()
//{
unsafe
{
//The Pointer Data Types will contain a memory address of the variable value.
//ampersand (&): The Address Operator. It is used to determine the address of a variable.
//asterisk (*): The Indirection Operator. It is used to access the value at an address.
int* p1=(int*)130, p2; //Valid syntax for making 2 pointers
//int *p3, *p4; //Invalid syntax for making 2 pointers.
//Maybe the compiler thinks it's: int* p3; int** p4; but in 1 statement.
//Declaring different types in 1 statement is illegal. int a, (float)b; is illegal
p2 = (int*)145; //location p2 is 145 in memory;
*p1 = 45; //value at location p1 = 45;
*p2 = 50; //value at location p2 = 50;
Console.WriteLine( $"adrs{(int)p1}-val{*p1}, adrs{(int)p2}-val{*p2}" );
int num = 10; //declare variable
int* p = # //store variable num's address location in pointer variable p
Console.WriteLine("Value :{0}", num);
Console.WriteLine("Address :{0}\n\n\n", (int)p);
}
//}
In regards to my questions, please tell me what to elaborate on because I am very clueless about what I don't know, meaning I don't know how to word my questions for easy comprehension.
Also, any DETAILED and understandable sources are greatly appreciated.