首页 > 解决方案 > 在 main 之外分配内存的问题

问题描述

作为 C 的初学者,我学会了一种奇特的方式来分配内存,struct{}以替换类似的东西ch1Buffer = calloc(u32Size, sizeof *ch1Buffer);并将它们放在外部int main{}以提高计算速度。但是,我的变量出现错误xThis declaration has no storage class or type specifier,您可以在代码一侧看到注释。我应该声明变量x还是?

这是我的示例代码:

#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;
}

标签: cdynamic-memory-allocation

解决方案


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.


推荐阅读