开发者

Declaration of array in c [duplicate]

开发者 https://www.devze.com 2023-03-20 14:38 出处:网络
This question already has answers here: Closed 11 years ago. 开发者_JAVA百科 Possible Duplicate: Stack variables vs. Heap variables
This question already has answers here: Closed 11 years ago. 开发者_JAVA百科

Possible Duplicate:

Stack variables vs. Heap variables

What is the difference between declaring an array as:

int arr[100];

and

int* arr=(int*)malloc(sizeof(int)*100);

Which one is preferred? Is there something like heap and stack memory involved in this?


I suggest a trip to the bookstore to pickup a copy of Kernighan and Ritchie's The C Programming Language, and optionally, a copy of Harbison & Steele's C: A Reference Manual.

The first case gives you an array of 100 ints, allocated on the stack. The latter case gives you a pointer to an int, whose address is that of a buffer allocated on the heap, the size of which is large enough to contain 100 ints.

The C language is fundamentally a hardware agnostic assembly language. The distinction between a pointer and an array is intentionally fuzzy, since array reference notation is syntactic sugar for pointer arithmetic. This:

int foo( int a )
{
  int x[100] = load_X() ;
  int y = x[ a ] ;
  return y ;
}

is identical to

int foo( int a )
{
  int *x     = load_X() ;
  int y      = *( x + a ) ;
  // note that the use of sizeof() isn't required.  For the pointer carries around
  // an implicit increment size (the size of the object to which it points). The above
  // is equivalent to
  //
  //   int y = *(int*)((char*)x + (a*sizeof(*x)) ) ;
}

Further, the compiler will (or should) whine about type mismatches, given function foo():

public void foo( int a[] )
{
  ...
}

The invocation:

int *p = malloc(...) ;

foo(p) ;

should results in a compiler whine regarding type mismatches.


The first one declares arr as an array of type int[100] that resides on the stack. In some contexts arr will decay to a pointer of type int *, but that doesn't make it a pointer. To further emphasize that it is not a pointer, sizeof(arr) will yield sizeof(int) * 100, not the size of an address.

The second one declares a pointer of type int * and initializes it to the pointer returned by malloc, which in fact allocates memory on the heap. Note that in this case arr is not an array - you can use the array notation to offset and dereference the pointer, but that doesn't make it an array.


The former allocates an automatic array of size 100, which will be automatically released once it goes out of scope.

The latter allocates space for 100 ints in the free store, and returns a pointer to the start of the block of memory. It will remain allocated until free() is called on the pointer.

If you need the memory only for as long as the current scope, then the former is easier to work with (assuming it's not too big.) Otherwise, the latter option is the approach to take.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号