c - 在 main 之外分配内存的问题
问题描述
作为 C 的初学者,我学会了一种奇特的方式来分配内存,struct{}
以替换类似的东西ch1Buffer = calloc(u32Size, sizeof *ch1Buffer);
并将它们放在外部int main{}
以提高计算速度。但是,我的变量出现错误x
:This 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;
}
解决方案
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.
推荐阅读
- blockchain - 使用 Web3 1.0 调用智能合约方法
- python-3.x - 为什么我们不能简单地打印“print(zip(a,b))”
- pentaho - 合并行(差异)是逐行比较,而不是一行与其他表的整行
- angularjs - 如何在angularjs中使用json在单个tr中打印两个不同的数组元素
- laravel - Laravel postgresql 连接错误。“运营商不存在”
- sockets - 如何在java中保持连接套接字
- php - Wordpress 分页不起作用,它不会移动到下一页
- python - 为什么 imap 和 smtp 需要单独的身份验证?
- typescript - 在 TypeScript 中选择并展平类型签名
- tfs - 构建期间的 TFS 2017 更改版本摘要说明