0

My code seems to operate fine when I do this, so I was just wondering if it was permissible or if it could lead to unexpected errors. I'm still learning how to deal with void*, and so I'm not entirely sure when I need to cast or (in this case) what exactly needs to be returned.

I have something like this:

struct x
{
   int i;
   char* s;
}

void* call_me(struct x* some_x)
{
   some_x->i = 5;
   some_x->s = "hello";

   return some_x;
}

I'm not sure what an alternative method would be here (beside to change the function return type, but I need to leave it as void*). Is this approach fine? It compiles and runs how I expect it to, but I'm not sure if that's just coincidental.

Why don't I have to return an object that's void*?

2
  • I haven't done C in a while, anyway I think that because you are passing a pointer to call_me the value of some_x will be changed so you don't need to return anything. From memory void * is used for function pointers Commented Aug 25, 2014 at 3:42
  • 1
    There is nothing wrong with this. And you needn't cast any of it. Commented Aug 25, 2014 at 3:50

3 Answers 3

1

Void* can be used to point to any type of data object, that's why you don't have to cast the pointer "some_x" to void*. But if you want to use the void* pointer to access the object's value, you'll have to use explicit type casting while dereferencing the void* pointer to tell the compiler the size of the object that is being pointed to.

Although, if you are passing a pointer in the function call, you don't really need to return it back anyways, the original copy will be altered by the function and it can be accessed directly later on.

Sign up to request clarification or add additional context in comments.

Comments

1

In C, the compiler can implicitly convert a typed pointer to a void pointer. This is perfectly valid, though it may not be safe because to use the pointer again, you will have to cast it to something else, and the compiler cannot check the validity of that for you.

Comments

1

You have a guarantee in C... it is simple, but powerful, you can convert from any data pointer type to void * and back again freely... this is the guarantee that allows you to do things that are like object oriented programming in std C.

see 6.3.2.3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.