Search code examples
cdynamic-memory-allocation

Problem to allocate memory outside the main


As a beginner in C, I learned a fancy way to allocate the memory with struct{} to replace something like ch1Buffer = calloc(u32Size, sizeof *ch1Buffer);and put them outside of the int main{} to boost up the calculation speed. However, I got an error on my variable x saying: This declaration has no storage class or type specifier, you can see the annotation on the side of the code. Should I declared the variable x or?

Here is my example code:

#include <stdio.h>

// New way for memory allocation 
struct {
    float ch1Buffer;
    double ch2Buffer;
    double ch2newBuffer;
} *x;
x = calloc(10, sizeof * x); // The error happened on the left side "x": This declaration has no storage class or type specifier

int main()
{
    int i,n;
    const int u32Size = 10;
    float* ch1Buffer = NULL;
    double* ch2Buffer = NULL;
    double* ch2newBuffer=NULL;
    
    
    int pBuffer[] = { 10,2,10,2,10,5,10,5,10,2 };
    int* pi16Buffer = pBuffer;

    // Old way for memory allocation
    //ch1Buffer = (float*)calloc(u32Size, sizeof* ch1Buffer);
    //ch2Buffer = (double*)calloc(u32Size, sizeof* ch2Buffer);
    //ch2newBuffer = (double*)calloc(u32Size, sizeof * ch2Buffer);

    

    // De-interveal the data to ch1Buffer and ch2Buffer
    for (i = 0; i < u32Size/2; i++)
    {
        ch1Buffer[i] += pi16Buffer[i * 2];
        ch2Buffer[i] += pi16Buffer[i * 2 + 1];
    }

    // Use memcpy to pick out the data we are interested
    memcpy(ch2newBuffer, &ch2Buffer[2], 2 * sizeof(ch2Buffer[0]));

    for (i = 0; i < 2; i++)
    {
        printf("a[%d] = %f\n", i, *ch2newBuffer);
        ch2newBuffer++;
    }


    free(ch1Buffer);
    free(ch2Buffer);
    return 0;
}

Solution

  • You can't do a malloc or calloc outside main or any other function. You can declare it at the beginning of your code if you need it as a global variable but you'll need to allocate the memory inside the main for example.

    typedef struct mystruct {
      float ch1Buffer;
      double ch2Buffer;
      double ch2newBuffer;
    }mystruct;
    
    mystruct* x;
    
    int main (void) {
        x = calloc(10, sizeof(mystruct)); // array of your structs
        if (!x) { // always check calloc return value
            perror("calloc");
            exit(EXIT_FAILURE);
        }
    
        /* do stuff */
    
        return 0;
    }
    
    

    Also I would suggest giving self-explanatory names to your structs for a better understanding of what it represents.