在C数组的声明 [英] Declaration of array in c

查看:154
本文介绍了在C数组的声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  堆栈变量与堆变量

什么是声明数组作为的区别是:

What is the difference between declaring an array as:

int arr[100];

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

哪一个是preferred?有什么样参与这个堆和栈内存?

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

推荐答案

我建议去一趟书店皮卡的副本Kernighan和里奇的的 C程序设计语言的和可选的副本哈比森&安培;斯蒂尔的 C:参考手册

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.

第一种情况为您提供了100整数数组,在栈上分配。后一种情况给你一个指针为int,其地址是在堆中分配的缓冲区,它的大小是大到足以容纳100整数。

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.

C语言基本上是一个硬件无关的汇编语言。一个指针和数组之间的区别是故意模糊的,因为数组引用标记是作为指针运算语法糖。这样的:

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 ;
}

是相同的

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)) ) ;
}

此外,编译器将(或应该)抱怨类型不匹配,给定函数富()

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

调用:

int *p = malloc(...) ;

foo(p) ;

应该产生一个编译器的抱怨有关类型不匹配。

should results in a compiler whine regarding type mismatches.

这篇关于在C数组的声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆