CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Sep 2013
    Posts
    16

    struct in memory explanation

    i read about the struct variables in the memory and i didnt understand
    when i calls to struct that i made for example :
    Code:
     public struct CarType
        {
            private string Color;
            private string car_type;
            private string car_model;
            private int speed;
            private bool starter;
    
    
            public void SetColor(string Color)
            {
                this.Color = Color;
            }
            
        }
    then the compiler automaticly creat 5 copy of the variables(from the struct) in the stack? or it creat a copy of the variables only when i calls method that use a variable from the struct , for example
    Code:
      public void SetColor(string Color)
            {
                this.Color = Color;
            }

  2. #2
    Join Date
    Jan 2010
    Posts
    1,133

    Re: struct in memory explanation

    No, when you declare a struct, the same rules apply as when you declare a class - but they behave differently in a very specific way.
    To actually create your struct in memory, you have to create one (in some code outside the struct, that uses it):

    CarType car = new CarType();

    The difference is that struct are value types, while classes are reference types. This means that, when you pass a struct to a function, or assign a it to another variable, the struct's instance is passed by value - it is copied. When you do the same with a class, both variables end up pointing to ghe same object. If you change a class-type object from within a function, the changes will remain when the function returns. This is called passing by reference (two things refer to the same object). If you do it to a struct, the changes will be lost, because you were changing a copy of the original.

    Also, people often say that structs are allocated on the stack, while classes are allocated on the heap - this is true, but this is an implementation detail of the language, it is not an intrinsic property of the concepts of structs and classes themselves. The important distinction is the by-value vs by-reference semantics.

    Write a few simple programs with some methods that take structs and classes as parameters and try it out yourself.

  3. #3
    Join Date
    Sep 2013
    Posts
    16

    Re: struct in memory explanation

    what happend in the memory when i write :
    Code:
    CarType car = new CarType();
    so i understand that in the stack after that i have 5 copyes of the struct variables ?
    and they are connected to the "car"?

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured