1

When is memory for a structure allocated in C? Is it when I declare it or when I create an instance of it? Also, why can static variables not be used within a struct?

  • 3
    What would a "static variable within a struct" mean? – Oliver Charlesworth Mar 13 '16 at 18:37
  • something like this: struct temp { static int a; }; when I create an instance of the above struct, the compiler says there is no member named 'a'. – Manali Kumar Mar 13 '16 at 18:46
  • 1
    A `struct` is _exactly_ the same as a variable. _Also, why can static variables not be used within a struct?_ : because it has not been designed into the C language. – Jabberwocky Mar 13 '16 at 18:55
  • Possible duplicate of [Where are static variables stored (in C/C++)?](http://stackoverflow.com/questions/93039/where-are-static-variables-stored-in-c-c) – Sudipta Kumar Sahoo Mar 13 '16 at 19:19
  • @Manali I think the question was not "How would I write it", but rather "what is it supposed to mean to the struct member" – tofro Mar 13 '16 at 19:54

1 Answers1

1

When you define a structure you are NOT allocating memory for it, that's the reason why you can use typedef to avoid writing struct my_struct_name. When you define a structure, you're declaring a data type that's why they don't take up data until you declare an instance of that structure.

struct point{   int x;  int y; };

This will not take up space until in a function or main you declare one like for example

int main(void){

    struct point mypoint1,mypoint2;//THIS IS WHEN MEMORY STARTS BEING ALLOCATED
    return 0;
}

Regarding the static, I don't think there's actually a point to declare a static to a structure? Why would you make an variable static to a structure?

Mr. Branch
  • 442
  • 2
  • 13
  • Thanks! That was helpful. Ok I realize I do not need to make a variable static within a struct. However, a variable explicitly declared auto within a struct also throws a compiler error saying no such member. Any idea why that might be happening? Aren't variables auto by default anyway? – Manali Kumar Mar 13 '16 at 20:03
  • Auto also makes sense to throw a compilation error since it deduces the data type. Suppose you define the same struct point I gave you put auto x; If in one point you put x=0, and another x=0.0 you'll have a problem. Also once Again I think there's actually no point, when you declare a structure you know what data types you're going to use inside of it. – Mr. Branch Mar 13 '16 at 20:08