我一直试图调用此函数,但我一直收到错误"标识符未找到" (是的,我知道我的变量名称不是最实用的。)
#include <stdio.h>
#include <stdlib.h>
typedef struct _POOL
{
int size;
void* memory;
} Pool;
int main()
{
printf("Enter the number of bytes you want to allocate\n");
int x = getchar();
allocatePool(x);
return 0;
}
Pool* allocatePool(int x)
{
Pool* p = (Pool*)malloc(x);
return p;
}
答案 0 :(得分:2)
也许您想要做的事情应该是这样的:
#include <stdio.h>
#include <stdlib.h>
typedef struct pool
{
int size;
void* memory;
} pool;
pool allocatePool(int x);
int main (int argc, char *argv[])
{
int x = 0;
pool *p = NULL;
printf("enter the number of bytes you want to allocate//>\n");
if (scanf("%d", &x) == 1 && x > 0 && (p = allocatePool(x)) != NULL)
{
// Do something using p
// ...
// Treatment is done, now freeing memory
free(p->memory);
free(p);
p = NULL; // Not useful right before exiting, but most often good practice.
return 0;
}
else
{
// Show a message error or do an alternative treatment
return 1;
}
}
pool allocatePool(int x)
{
pool *p = malloc(sizeof(pool));
if (p != NULL)
{
p->memory = malloc(x);
p->size = (p->memory == NULL) ? 0 : x;
}
return p;
}
答案 1 :(得分:0)
我认为你的程序应该是这样的:
#include <stdio.h>
#include <stdlib.h>
typedef struct _Pool
{
int size;
void* memory;
} Pool;
Pool* allocatePool(int x)
{
static Pool p;//no pointer here you also need memory for your integer or you have to allocate memory for the integer too
p.size=x;
p.memory=malloc(x);//just allocate memory for your void pointer
return &p;//return the adress of the Pool
}
int main()
{
printf("enter the number of bytes you want to allocate//>\n");
int x;
scanf("%d", &x);//if you use getchar() for reading you pass the ascii value of the number not the normal number
allocatePool(x);
return 0;
}