C/C++ 中的 float* 和 float[n] 有什么区别

What is the difference between float* and float[n] in C/C++

使用有什么区别

float* f;

float f[4];

或者他们的待遇完全一样?使用一个而不是另一个可能会导致您 运行 陷入内存分配问题吗?如果不是,是否存在区别对待的情况?

不知道这是否相关,但我使用 float* 类型作为函数参数。例如:

void myfun(float* f){
     f[0] = 0;
     f[1] = 1;
     f[2] = 2;
     f[3] = 3;
}

可以编译并且 运行 很好(我不太确定为什么 - 我认为因为我没有为 f 分配任何内存所以它会抛出某种异常).

float* f;

它是一个指向 float 类型变量的指针

float f[4];

它是一个名为 f 的数组变量,类型为 float,大小为 4

使用有什么区别

浮动* f;

浮动 f[4];

Or are they treated the exact same way?

没有

Will using one over the other potentially cause you to run into memory allocation issues?

你不应该用一个代替另一个,你可能会面临多个问题,而不仅仅是内存相关的问题。

If not, are there ANY situations where they are treated differently?

除了场景数组和指针声明可互换为函数形式参数外,它们总是以不同的方式对待。

which compiles and runs fine (I'm not really sure why - I would think that since I didn't allocate any memory to f that it would throw some kind of exception).

这种情况在上面的回答中作为例外进行了解释。

阅读arrays and pointers

"I would think that since I didn't allocate any memory to f that it would throw some kind of exception)."

不,如果您没有为 f 适当地分配内存,取消引用只是 未定义的行为。保证没有例外。

你的冰箱可能会吃掉你的猫,以防...

float f[4]

是分配自动存储的数组(一般是栈)

float* f;

是一个指针,除了指针的大小外,它本身没有分配。它可以指向单个浮点值,或使用自动或动态存储(堆)分配的浮点数组

未分配的指针通常指向随机内存,因此如果将其传递给 myfun 函数,您将得到未定义的行为。有时它似乎可以工作(覆盖它指向的任何随机内存),有时它会除外(尝试写入无效或不可访问的内存)

他们在许多情况下受到相同的对待,而在其他情况下则不同。即 sizeof(f) 会有所不同。