gpt4 book ai didi

c - 尝试在 c 中分配内存函数?

转载 作者:行者123 更新时间:2023-11-30 21:35:21 25 4
gpt4 key购买 nike

我一直在尝试调用这个函数,但我不断收到错误“找不到标识符”(是的,我知道我的变量名不是最实用的)。

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

最佳答案

也许你想做的应该是这样的:

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

关于c - 尝试在 c 中分配内存函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36112446/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com