C编程:malloc()在另一个函数中我需要帮助malloc() 在另一个函数中.我经过一个指针和大小从我的main()我想为这个指针动态地分配内存malloc()但我看到的是.正在分配的内存用于在我调用的函数中声明的指针,而不是用于在main().如何将指针传递给函数并为传递的指针分配内存从调用函数内部?我编写了以下代码,并得到如下所示的输出。资料来源:int main(){
unsigned char *input_image;
unsigned int bmp_image_size = 262144;
if(alloc_pixels(input_image, bmp_image_size)==NULL)
printf("\nPoint2: Memory allocated: %d bytes",_msize(input_image));
else
printf("\nPoint3: Memory not allocated");
return 0;}signed char alloc_pixels(unsigned char *ptr, unsigned int size){
signed char status = NO_ERROR;
ptr = NULL;
ptr = (unsigned char*)malloc(size);
if(ptr== NULL)
{
status = ERROR;
free(ptr);
printf("\nERROR: Memory allocation did not complete successfully!");
}
printf("\nPoint1: Memory allocated: %d bytes",_msize(ptr));
return status;}程序输出:Point1: Memory allocated ptr: 262144 bytesPoint2: Memory allocated input_image: 0 bytes
3 回答
BIG阳
TA贡献1859条经验 获得超6个赞
int main(){
unsigned char *input_image;
unsigned int bmp_image_size = 262144;
if(alloc_pixels(&input_image, bmp_image_size) == NO_ERROR)
printf("\nPoint2: Memory allocated: %d bytes",_msize(input_image));
else
printf("\nPoint3: Memory not allocated");
return 0;}signed char alloc_pixels(unsigned char **ptr, unsigned int size) {
signed char status = NO_ERROR;
*ptr = NULL;
*ptr = (unsigned char*)malloc(size);
if(*ptr== NULL)
{
status = ERROR;
free(*ptr); /* this line is completely redundant */
printf("\nERROR: Memory allocation did not complete successfully!");
}
printf("\nPoint1: Memory allocated: %d bytes",_msize(*ptr));
return status; }
慕田峪9158850
TA贡献1794条经验 获得超8个赞
如何将指针传递到函数并从调用函数内部为传递的指针分配内存?
int
int foo(void){
return 42;}int*int):
void foo(int* out){
assert(out != NULL);
*out = 42;}T*
T* foo(void){
T* p = malloc(...);
return p;}void foo(T** out){
assert(out != NULL);
*out = malloc(...);}
aluckdog
TA贡献1847条经验 获得超7个赞
void allocate_memory(char **ptr, size_t size) {
void *memory = malloc(size);
if (memory == NULL) {
// ...error handling (btw, there's no need to call free() on a null pointer. It doesn't do anything.)
}
*ptr = (char *)memory;}int main() {
char *data;
allocate_memory(&data, 16);}- 3 回答
- 0 关注
- 852 浏览
添加回答
举报
0/150
提交
取消
