Chapter140:Pointers

No Comments

Section140.1:Pointersforarrayaccess

ThisexampledemonstrateshowpointerscanbeusedforC-likeaccesstoC#arrays.

unsafe

{

varbuffer=newint[1024];

fixed(int*p=&buffer[0])

{

for(vari=0;i<buffer.Length;i++)

{

*(p+i)=i;

}

}

}

The unsafekeyword is required because pointer access will not emit any bounds checks that are normally emitted when accessing C# arrays the regular way.

ThefixedkeywordtellstheC#compilertoemitinstructionstopintheobjectinanexception-safeway.Pinningis requiredtoensurethatthegarbagecollectorwillnotmovethearrayinmemory,asthatwouldinvalidateany pointerspointingwithinthearray.

Section140.2:Pointerarithmetic

Addition and subtraction in pointers works differently from integers. When a pointer is incremented or decremented, the address it points to is increased or decreased by the size of the referent type.

Forexample,thetypeint(aliasforSystem.Int32)hasasizeof4.Ifanintcanbestoredinaddress0,the subsequentintcanbestoredinaddress4,andsoon.Incode:

varptr=(int*)IntPtr.Zero;

Console.WriteLine(newIntPtr(ptr));//prints0 ptr++;

Console.WriteLine(newIntPtr(ptr));//prints4

ptr++;

Console.WriteLine(newIntPtr(ptr));//prints8

Similarly,thetypelong(aliasforSystem.Int64)hasasizeof8.Ifalongcanbestoredinaddress0,thesubsequent

longcanbe stored in address8, and so on. Incode:

varptr=(long*)IntPtr.Zero;

Console.WriteLine(newIntPtr(ptr));//prints0 ptr++;

Console.WriteLine(newIntPtr(ptr));//prints8

ptr++;

Console.WriteLine(newIntPtr(ptr));//prints16

The type voidis special and voidpointers are also special and they are used as catch-all pointers when the type isn’t known or doesn’t matter. Due to their size-agnostic nature, voidpointers cannot be incremented or decremented:

varptr=(void*)IntPtr.Zero;

Console.WriteLine(new IntPtr(ptr));

ptr++;//compile-timeerror

Console.WriteLine(new IntPtr(ptr));

ptr++;//compile-timeerror

Console.WriteLine(new IntPtr(ptr));

Section140.3:Theasteriskispartofthetype

InCandC++,theasteriskinthedeclarationofapointervariableispartoftheexpressionbeingdeclared.InC#,the asterisk in the declaration is part of the type.

InC,C++andC#,thefollowingsnippetdeclaresanintpointer:

int*a;

InCandC++,thefollowingsnippetdeclaresanintpointerandanintvariable.InC#,itdeclarestwointpointers:

int*a,b;

InCandC++,thefollowingsnippetdeclarestwointpointers.InC#,itisinvalid:

int*a,*b;

Section140.4:void*

C#inheritsfromCandC++theusageofvoid*asatype-agnosticandsize-agnosticpointer.

void*ptr;

Anypointertypecanbeassignedtovoid*usinganimplicitconversion:

int*p1=(int*)IntPtr.Zero;

void*ptr=p1;

Thereverserequiresanexplicitconversion:

int*p1=(int*)IntPtr.Zero;

void*ptr=p1;

int*p2=(int*)ptr;

Section140.5:Memberaccessusing->

C#inheritsfromCandC++theusageofthesymbol->asameansofaccessingthemembersofaninstance through a typed pointer.

Considerthefollowingstruct:

structVector2

{

publicintX;

publicintY;

}

Thisisanexampleoftheusageof->toaccessitsmembers:

Vector2v;

v.X=5;

v.Y=10;

Vector2* ptr = &v;

intx=ptr->X;

inty=ptr->Y;

strings=ptr->ToString();

Console.WriteLine(x);//prints5

Console.WriteLine(y);//prints10

Console.WriteLine(s);//printsVector2

Section140.6:Genericpointers

Thecriteriathatatypemustsatisfyinordertosupportpointers(see Remarks)cannotbeexpressedintermsof generic constraints. Therefore, any attempt to declare a pointer to a type provided through a generic type parameter will fail.

voidP<T>(Tobj)

whereT:struct

{

T*ptr=&obj;//compile-timeerror

}

About us and this blog

We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.

Request a free quote

We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.

Subscribe to our newsletter!

More from our blog

See all posts
No Comments

Leave a Comment