Changing the address of a New struct in a loop?!

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • superhero
    New Member
    • May 2010
    • 2

    Changing the address of a New struct in a loop?!

    Hi guys,
    i'm writing a simple code which is about polynomials using link lists in C#. the problem i have is that whenever it creates a new struct (node) in the for loop it gives it the same address as the previous node was given. so how do i fix it ? here is my struct :

    struct poly { public int coef; public int pow; public poly* link;} ;

    and here is the where the problem occurs:


    for (; i < this.textBox1.T ext.Length; i++)
    {
    q = new poly();
    ......
    p->link = &q;
    }
    //&q remains unchanged!
    //p.s. the class is unsafe too
    //edit, its C# but i have to make it look like C so i'm not allowed to use linked lists
  • GaryTexmo
    Recognized Expert Top Contributor
    • Jul 2009
    • 1501

    #2
    I've been curious about unsafe code in C# so I did a bit of googling around and found this page...

    A broad category of Microsoft tools, languages, and frameworks for software development. Designed to support developers in building, debugging, and deploying applications across various platforms.


    It looks like you're creating the poly incorrectly. Instead of...

    Code:
    poly q = new poly();
    p->link = &q;
    ... you want ...
    Code:
    IntPtr newP = Marshal.AllocHGlobal(sizeof(poly));
    poly* q = (poly*)newP.ToPointer();
    p->link = q;
    In the future, give google a try first before posting a question. I realize sometimes google doesn't help if you're not sure what you're looking for but in this case, "C# unsafe linked list" turned up the above link fairly easily. With stuff like this, chances are someone has done it before so a quick google can save you a lot of time :)

    Comment

    • superhero
      New Member
      • May 2010
      • 2

      #3
      THX a bunch dude :) . you made my day. actually i did thousands of searches except the one u did :D . i was searching about polynomials so yeah...
      so previously "q" was'nt a pointer but now with what you said i made it a otherwise i had work it out with "fixed (){} " >.>
      thx again

      Comment

      Working...