Dynamically allocating memory for an array of floats

1.8k Views Asked by At

While trying to understand some code in C++ I came across the following code (and trying to understand its meaning):

int SIZE = 256;
float* A = (float *) malloc(SIZE * sizeof(float*));
for (int i=0; i<M*K; i++) { A[i] = 0.0; }

I wanted to ask, how is the above different from the following:

float* A = (float *) malloc(SIZE * sizeof(float));

When I compile the code, both of the versions of "float* A=" compile and execute ok.

2

There are 2 best solutions below

5
jwdonahue On

...I wanted to ask, how is the above different from the following...

sizeof(float*) is the size of a pointer to float. On most systems that's whatever number of bytes there are in a pointer, often, but not always, the size of hardware address registers. sizeof(float) is the number of bytes in a float, which may or may not be the same size as a pointer.

1
Rezaeimh7 On

Float* is pointer. Regardless of what data type a pointer is pointing to, its size is fixed and is 32 bits On 32-bit machine and 64 bit on 64 bit machine.