I'm passing variable cn to function myconnect by pointer. While stepping in the debugger the cn is correct inside of myconnect(). But no more in main(). Can't I do this like that (see code below)? When I do the initialization and connection in main, it works. And I can pass cn to other functions. But I would prefer to exclude it from there(main) and have in separate function.

int myconnect(OCI_Connection* cn  )
{
  if (!OCI_Initialize(err_handler, NULL, OCI_ENV_DEFAULT))
  return 0;
  cn = OCI_ConnectionCreate( DB, DBUSER, DBPASS, OCI_SESSION_DEFAULT);
  if (cn == NULL) return 0;

  return 1;
}

int main()
{
  OCI_Connection* cn;

  if (myconnect(cn) == 0)
  {
    dbErr =1;
  }
}
有帮助吗?

解决方案

The variable cn is passed by value to the function myconnect, i.e. the function receives a copy and assign a value to that copy. This has no effect in main.

To have a effect, you have to passed it by reference. In C, that means you have to pass a pointer to the variable, which is itself a pointer:

int myconnect(OCI_Connection** cn)
{
  if (!OCI_Initialize(err_handler, NULL, OCI_ENV_DEFAULT))
      return 0;
  *cn = OCI_ConnectionCreate(DB, DBUSER, DBPASS, OCI_SESSION_DEFAULT);
  if (*cn == NULL)
      return 0;

  return 1;
}

int main()
{
  OCI_Connection* cn;

  if (myconnect(&cn) == 0)
  {
    dbErr =1;
  }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top