我在C语言程序中有以下语句,无法更改:
struct struct_handle;
struct struct_handle *com_Connect(const char *val1, void *priv, int timeout_msec, enum com_ErrorCodes *com_errno);
我创建了这个功能:
void foo(struct_handle *handle)
{
enum com_ErrorCodes com_errno;
do
{
handle = com_Connect("val1", NULL, 10000, &com_errno);
if(handle == NULL)
{
//ERROR handle is NULL
}
}
while(handle == NULL);
//HERE handle is not NULL
}
这是主要功能:
int main(int argc, char const *argv[])
{
struct struct_handle *handle;
foo(handle);
if(handle == NULL)
{
//ALWAYS handle IS NULL
}
return 0;
}
我创建的foo()函数是要发送一个“句柄”并在它与NULL不同时接收它,我知道它与NULL不同,因为该函数返回并且我已经验证了函数内部的内容。问题是,当我想在函数外使用该“句柄”时,它总是告诉我它为NULL,这使我认为问题出在我从函数返回时,我没有正确获取指针的内容。正确的获取方式是什么?
答案 0 :(得分:4)
在C中,所有功能参数均按值传递。这意味着对handle
中的参数foo
的任何更改都不会反映在调用函数中。
您应该更改foo
以返回struct_handle *
,并将其分配给handle
中的main
。
将功能更改为:
struct_handle *foo()
{
enum com_ErrorCodes com_errno;
struct_handle *handle;
do
{
handle = com_Connect("val1", NULL, 10000, &com_errno);
if(handle == NULL)
{
//ERROR handle is NULL
}
}
while(handle == NULL);
return handle;
}
并这样称呼它:
handle = foo();