huzaifa shabbir hussain

I am sending you UNSAFE Code in which I am trying to implement Linked List like we used to do in C. What I believe is that the following line of code should allocate new memory address on each iteration ¡°test1 = new LinkListPtr();¡± but in fact it is not. See if you can figure it out what wrong with it.

class Program

{

unsafe public struct LinkListPtr

{

public int num;

public LinkListPtr* linkListPtr;

}

unsafe static void Main(string[] args)

{

LinkListPtr* cur=null;

LinkListPtr* first=null;

LinkListPtr* obj=null;

LinkListPtr test1;

for (int i = 0; i < 3; i++)

{

if (first == null)

{

LinkListPtr test = new LinkListPtr();

first =&test;

first->num = i;

first->linkListPtr = null;

}

else

{

cur = first;

while (cur->linkListPtr != null)

{

//I am stuck into a continuous loop

cur = cur->linkListPtr;

}

test1 = new LinkListPtr();

obj = &test1;

obj->num=i;

obj->linkListPtr = null;

cur->linkListPtr = obj;

}

}

while (first != null)

{

Console.WriteLine(first->num);

first = first->linkListPtr;

}

Console.ReadLine();

}

}

}



Re: Visual C# Language Problem with Pointers in C#

Nimrand

Are you doing this as a coding exercise If not, .NET already has a linked list: System.Collections.Generics.LinkedList. Also, it is implemented without unsafe code.

Also, using the new operator with structs allocates the struct on the stack, not the heap. I'm not sure if this is true with unsafe structs, but it would explain your program's behavior.





Re: Visual C# Language Problem with Pointers in C#

timvw

I would agree with Nimrand, the new instance seems to be allocated on the stack (and always the same place/address on that stack), which explains why from the second element you see that node->link points to node...