C编程:Malloc()在另一个功能中
我需要有关 malloc()
在另一个函数内的帮助。
我正在将指针和大小从我的main()
传递给函数,并且我想使用<动态为该指针分配内存code>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 bytes
Point2: Memory allocated input_image: 0 bytes
I need help with malloc()
inside another function.
I'm passing a pointer and size to the function from my main()
and I would like to allocate memory for that pointer dynamically using malloc()
from inside that called function, but what I see is that.... the memory, which is getting allocated, is for the pointer declared within my called function and not for the pointer which is inside the main()
.
How should I pass a pointer to a function and allocate memory for the passed pointer from inside the called function?
I have written the following code and I get the output as shown below.
SOURCE:
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;
}
PROGRAM OUTPUT:
Point1: Memory allocated ptr: 262144 bytes
Point2: Memory allocated input_image: 0 bytes
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
问问自己:如果您必须编写一个必须返回 int 的函数,您会怎么做?
您可以直接返回它:
或者通过添加间接级别通过输出参数返回它(即,使用
int*
而不是int
):因此,当您返回指针类型 (
T*
) 时,它是相同的事情:你要么直接返回指针类型:要么添加一个间接级别:
Ask yourself this: if you had to write a function that had to return an
int
, how would you do it?You'd either return it directly:
or return it through an output parameter by adding a level of indirection (i.e., using an
int*
instead ofint
):So when you're returning a pointer type (
T*
), it's the same thing: you either return the pointer type directly:or you add one level of indirection:
您需要将一个指向指针的指针作为参数传递给您的函数。
You need to pass a pointer to a pointer as the parameter to your function.
如果您希望您的功能修改指针本身,则需要将其作为指针指向指针。这是一个简化的例子:
If you want your function to modify the pointer itself, you'll need to pass it as a pointer to a pointer. Here's a simplified example:
您需要通过参考而不是通过copy 传递指针,,函数
alloc_pixels中的参数
需要ampersand&amp;要退回指针的地址 - 即通过参考在c Speak中通过参考来调用。我已经评论了两行
free(ptr)
和“错误:...”alloc_pixels
函数,这是令人困惑的。如果内存分配失败,则不需要免费
指针。编辑:查看 msdn> msdn 由OP提出的建议,代码示例与我答案的早期相同。...但是...将格式指定符更改为
>%u
的size_t
type ,在printf(...)中
在main()
中调用。You need to pass the pointer by reference, not by copy, the parameter in the function
alloc_pixels
requires the ampersand & to pass back out the address of the pointer - that is call by reference in C speak.I have commented out the two lines
free(ptr)
and "ERROR: ..." within thealloc_pixels
function as that is confusing. You do not need tofree
a pointer if the memory allocation failed.Edit: After looking at the msdn link supplied by OP, a suggestion, the code sample is the same as earlier in my answer.... but...change the format specifier to
%u
for thesize_t
type, in theprintf(...)
call inmain()
.如其他答案中所述,我们需要指向指针的指针。但为什么?
我们需要通过指针传递该值,以便能够修改值。如果要修改
int
,则需要通过int*
将其传递。在这个问题中,我们要修改的值是指针
int*
(指针从null
更改为分配内存的地址),因此我们需要传递指针到指针int **
。通过遵循,
pint
内部foo(int*)
是参数的副本。当我们将内存分配给本地变量时,main()
中的一个是完整的。因此,我们需要指针指针,
As mentioned in the other answers, we need a pointer to the pointer. But why?
We need to pass the value by a pointer in order to be able to modify the value. If you want to modify an
int
, you need to pass it by theint*
.In this question, the value we want to modify is a pointer
int*
(pointer changed fromNULL
to the address of the allocated memory), so we need to pass a pointer to the pointerint**
.By doing followed,
pInt
insidefoo(int*)
is a copy of the argument. When we allocate memory to the local variable, the one in themain()
is intact.So we need a pointer to pointer,
这是没有意义的:
alloc_pixels
返回一个signed char
(ERROR
或NO_ERROR
),然后将其与< code>NULL (应该用于指针)。如果您希望更改
input_image
,则需要将指向它的指针传递给alloc_pixels
。alloc_pixels
签名如下:您可以这样调用它:
内存分配
This does not make sense :
alloc_pixels
returns asigned char
(ERROR
orNO_ERROR
) and you compare it toNULL
(which is supposed to be used for pointers).If you want
input_image
to be changed, you need to pass a pointer to it toalloc_pixels
.alloc_pixels
signature would be the following:You would call it like this:
And the memory allocation
在您的初始代码中,当您将Input_image传递到函数Alloc_pixels时,编译器正在创建IT(即PTR)的副本并将该值存储在堆栈上。您将Malloc返回的值分配给PTR。一旦函数返回MAIN,并且堆栈放松一下,则该值就会丢失。因此,内存仍在堆上分配,但是内存位置从未存储在(或分配给)input_image中,因此问题。
您可以更改函数Alloc_pixels的签名,该函数更简单地理解,也不需要其他“状态”变量。
您可以在主要以上调用上述函数:
In your initial code , when you were passing input_image to the function alloc_pixels, compiler was creating a copy of it (i.e. ptr) and storing the value on the stack. You assign the value returned by malloc to ptr. This value is lost once the function returns to main and the stack unwinds. So, the memory is still allocated on heap but the memory location was never stored in (or assigned to )input_image, hence the issue.
You can change the signature of the function alloc_pixels which would be simpler to understand, and you won't require the additional 'status' variable as well.
You can call the above function in main :
在尝试解决此问题之前,您应该知道2点:
1。 c函数:传递给该函数的所有参数将是函数中的副本。
这意味着您在函数中完成的每个任务都不会影响功能之外的变量,实际上是在复制上实际上:
因此,如果您想在功能中更改i,则需要知道事物与其副本之间的区别:
那是他们的唯一区别。
因此,更改i在功能中的唯一方法是使用i的地址。
例如,有一个新的函数fun_addr:
这样,您可以更改我的价值。
fun_addr函数的关键点是,您已将地址传递给该功能。您可以更改存储在该地址中的值。
Malloc会做什么?
Malloc将分配一个新的内存空间,返回指向该地址后面的指针。
查看此说明:
您正在做的是让Array的值等于Malloc返回的地址。
看?这是一个相同的问题,将值永久分配给传递给该函数的参数。此时,该值为
地址
。因此,代码应该是:
该代码将起作用。
There are 2 points that you should know before you attempt to solve this problem:
1. C Function: All the parameters you passed to the function will be a copy in the function.
That means every assignment that you've made in the function will not affect the variables outside the function, you're working on the copy actually:
So, if you want to change i in the function, you need to know the difference between the thing and its copy:
And that's their only difference.
So the only way to change i in the function is using the address of i.
For example, there's a new function fun_addr:
In this way, you could change i's value.
The key point in the fun_addr function is, you've passed a address to the function. And you could change the value stored in that address.
What will malloc do?
malloc will allocate a new memory space, and return the pointer pointed to that address back.
Look at this instruction:
What you are doing is let array's value equals to the address returned by malloc.
See? This is the same question, permanently assigning value to the parameter passed to the function. At this point, the value is
address
.So the code should be:
This one will work.
我可以将指针指向指针解决方案来解决此功能的类似问题的唯一方法
是分配一个临时指针来存储地址
,然后将其重新分配给它
任何评论,以指出为什么直接使用“* pszbmpfile”直接与globalalloc didn'使用“* pszbmpfile” T工作将不胜感激。
我回答了自己的问题。我忘了在其他代码行中使用pszbmpfile携带“*”。所有贡献者的好教训。非常感谢。
The only way I could get pointer to a pointer solution to work for a similar problem I was having for this function
Was by assigning a temporary pointer to store the address
then reassigning it
Any comment on why using "* pszBMPFile" directly with GlobalAlloc didn't work would be appreciated.
I answered my own question. I forgot to carry the "*" through with pszBMPFile in the other lines of code. Good lessons from all the contributors. Many thanks.