CodeKingPlusPlus
CodeKingPlusPlus

Reputation: 16081

C pointer array allocation

When are variables in main() allocated? Especially how much memory is allocated for the pointer to arrays arr and 2d in the following:

int main()
{
  float a, b;
  int *b;
  float *(arr)[6];
  float *(2d)[5][5];
}

Are these considered auto, global, or static?

Upvotes: 0

Views: 156

Answers (2)

rashok
rashok

Reputation: 13414

Memory for all the local variables declared inside a function will be allocated during run time, before executing a function. For each function an activation record will be created in the stack of the process memory, which will contains all the local variables. Once the function execution is completed activation record will be poped out.

All the variables declared inside a function are consider as auto only, unless it is explicitly declared as static or register. Variables declared outside a function will be considered as global.

If a variable is declared inside or outside a function as static, means memory allocation will be done at compile time itself, which will be in data segment(or bss).

All the pointer variable is going to store some virtual address(of variable of any type or function). So size of a pointer variable is 4 bytes in case of 32 bit machine and 8 bytes in case of 64 bit machine.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

All these variables are automatic: global variables need to be declared outside the scope of a function; static variables need to have a static modifier.

The exact size is system-dependent. You can find out by printing sizeof(arr), sizeof(b), etc.

The exact time of allocation of automatic variables is compiler-dependent: some of them are allocated upon entering the function, some are upon entering a block where they are used, and some may be optimized out, and not allocated at all.

Upvotes: 2

Related Questions