1

I have a little question - when I define array like this:

int arr[10];

and I do something like that:

func(arr);

I know that the arr is sent by reference and not by value , but , does it says the array is in the heap? no, of course not. so how it's works in the stack? thanks ahead!

user3467955
  • 561
  • 5
  • 11
  • 1
    It depends if you declare it in a function or at a global level. If it is at the global level, then it is not on the stack (or heap) but in the data segment. – George Houpis Dec 18 '14 at 22:51
  • 3
    It's not "sent by reference". It decays to a pointer (`func` receives a a pointer to `arr`). It's a pointer to an array on the stack, it has nothing to do with the heap. – Red Alert Dec 18 '14 at 22:51
  • This question is very similar to one I answered a few days ago: http://stackoverflow.com/questions/27381502/difference-cstring-sstring/27383750#27383750 – Nick Dec 18 '14 at 23:26
  • The passing array to the function has nothing to do with the array's storage area. The array is stored where it's stored, and arrays in any storage area can be passed to a function. – M.M Dec 19 '14 at 05:17
  • @RedAlert It is [passed by reference](http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_reference). The function receives a token which can be used to refer to the original object. – M.M Dec 19 '14 at 05:19

3 Answers3

4

It's in the stack OR in the bss (uninitialized data section). In any case, what you are passing to func is a pointer to the address of the first element of the array, through which you can index all the other ones. Think of pointers as integers that map to specific locations in RAM memory, like GPS coordinates of byte granularity or something like that. That address can be in any location in memory, not just the heap. Just my 2cents

  • so you're actually saying that the pointer isn't in the heap until I use dynamic allocation? – user3467955 Dec 18 '14 at 22:57
  • Yep, you can get a pointer from any variable. See this: `int foo[4]; /* in stack */ int *foo_ptr = foo;` and `int * foo_ptr = malloc(4 * sizeof(int)); /* in heap */` then you can use it the same way `foo_ptr[1] = 0;` – alex94puchades Dec 18 '14 at 22:59
1

For array the memory will be allocated during the compile time itself, and the memory space will be allocated in the stack. If you are using pointers, then the memory should be allocated dynamically, and the memory space will be allocated in the heap memory.

sharon
  • 734
  • 6
  • 15
0

Compiling and running the code :

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int arr[10];
    printf("arr = %p\n",arr);   
    sleep(50);  
    exit(0);
}

followed by pmap PID_of_the_process gives me :

00007f68a084b000 8K rw--- [ anon ]

00007fff4a991000 84K rw--- [ stack ]

00007fff4a9ff000 4K r-x-- [ anon ]

ffffffffff600000 4K r-x-- [ anon ]

Since the code is printing : arr = 0x7fff4a9a4480

It shows that arr is allocated on the stack here.

Hope this helps.

IbliSS
  • 25
  • 1
  • 7