Matrix of floats, pls explain

I am running a code to generate kernel or matrix. I see it works, but it is not clear to me how. Author of the code declares the ret as pointer to float. But I see he uses it as array:
1
2
3
ret = malloc(sizeof(float) * size * size);
...
ret[ y*size+x] = ...

Can you explain me how is this possible? I thought that one should explicitly define array of floats. How he can even access it as array?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//creates a gaussian kernel
float* createGaussianKernel(uint32_t size,float sigma)
{
    float* ret;
    uint32_t x,y;
    double center = size/2;
    float sum = 0;
    //allocate and create the gaussian kernel
    ret = malloc(sizeof(float) * size * size);
    for(x = 0; x < size; x++)
    {
        for(y=0; y < size; y++)
        {
            ret[ y*size+x] = exp( (((x-center)*(x-center)+(y-center)*(y-center))/(2.0f*sigma*sigma))*-1.0f ) / (2.0f*PI_*sigma*sigma);
            sum+=ret[ y*size+x];
        }
    }
    //normalize
    for(x = 0; x < size*size;x++)
    {
        ret[x] = ret[x]/sum;
    }
    //print the kernel so the user can see it
    printf("The generated Gaussian Kernel is:\n");
    for(x = 0; x < size; x++)
    {
        for(y=0; y < size; y++)
        {
            printf("%f ",ret[ y*size+x]);
        }
        printf("\n");
    }
    printf("\n\n");
    return ret;
}
Last edited on
Syntactic sugar of pointer math:
1
2
3
4
5
int * p;

*p == *(p + 0) == p[0]

*(p + 7) == p[7]

The difference between array and pointer is that array has memory allocated for its elements, but pointer does not. Pointer may be null, point to object, or point to object (that happens to be in array of objects of same type).

Your ret is set to point to float object that happens to be the first in an array of size^2 floats.
keskiverto:
I thought that the float size is fixed. So when he declares float* ret;
so it should point to object of size sizeof(float). Hence I am surprised, that it is possible to change the size of the object to sizeof(float) * size * size ... it sounds strange to me, like redeclaration. If you declare you will use variable A with size of 12 bytes for example, and then you change the size of the variable to e.g 64 bytes, it does not make sense to me.
The size is fixed.
1
2
float foo;
float bar[ size ];

Do you think that bar is a single object that consumes size*sizeof(float) bytes?

You should answer no. If you do, what is this:
1
2
float bar[ size ];
float * gaz = bar;

The above can be written more explicitly:
float * gaz = &(bar[0]);

Lets have more fun:
1
2
3
float * p2 = &(bar[2]);
++gaz;
assert( gaz + 1 == p2 );
Topic archived. No new replies allowed.