用值初始化数组(指针) [英] Initializing array (pointer) with values

查看:158
本文介绍了用值初始化数组(指针)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,在C语言中,这非常有效:

So, in C, this perfectly works:

int myArray[] = {1, 2, 3};

为什么以下内容在访问元素时给我一个运行时错误?

why does the following give me a runtime error when accessing an element?

int * myArray2 = {1, 2, 3};
myArray2[0];

myArray2[0]基本上是*myArray2的意思,这也不起作用吗?

when myArray2[0] basically means *myArray2, which does also not work?

推荐答案

我认为根本的区别在于,声明数组隐式分配内存,而声明指针则不会.

I think that the fundamental difference is that declaring an array implicitly allocates memory, while declaring a pointer does not.

int myArray[3];声明一个数组,并为3个int值分配足够的内存.

int myArray[3]; declares an array and allocates enough memory for 3 int values.

int myArray[] = {1,2,3};是一个小的语法糖,它使数组的大小由初始化值确定.就内存分配而言,最终结果与前面的示例相同.

int myArray[] = {1,2,3}; is a little syntactic sugar that lets the size of the array be determined by the initialization values. The end result, in terms of memory allocation, is the same as the previous example.

int *myArray;声明一个指向int值的指针.它不会为int值的存储分配任何内存.

int *myArray; declares a pointer to an int value. It does not allocate any memory for the storage of the int value.

int *myArray = {1,2,3};语法.我希望您会为此遇到编译器错误. (但是多年以来,我还没有进行过真正的C编码.)即使编译器允许通过,分配也会失败,因为没有分配内存来存储值.

int *myArray = {1,2,3}; is not supported syntax as far as I know. I would expect you would get a compiler error for this. (But I haven't done actual C coding in years.) Even if the compiler lets it through, the assignment fails because there is no memory allocated to store the values.

虽然您可以使用数组语法来引用指针变量,但这仅在分配了内存并将其地址分配给指针的情况下才有效.

While you can deference a pointer variable using array syntax, this will only work if you have allocated memory and assigned its address to the pointer.

这篇关于用值初始化数组(指针)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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