Search code examples
cpointersstatic-memory-allocation

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


What is the difference between using

float* f;

and

float 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?

Don't know if this is relevant, but I'm using the type float* as a function argument. For example:

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

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).


Solution

  • float f[4]
    

    is an array that is allocated with automatic storage (typically the stack)

    float* f;
    

    is a pointer, which by itself has no allocation other than the size of a pointer. It can point to a single floating point value, or an array of floats that was allocated with either automatic or dynamic storage (heap)

    An unallocated pointer typically points to random memory, so if you pass it into your myfun function, you will get undefined behavior. Sometimes it may seem to work (overwriting whatever random memory it is pointing too), and sometimes it will except (trying to write to invalid or inaccessible memory)

    They are treated the same in many situations, and not in others. i.e. sizeof(f) will be different.