2

I'm new into C and I'm trying to get a grip on pointers. I came across this expression

char *foo = *(char **)bar;

what exactly is going on? I understand that * is pointer ** is pointer to pointer, but I don't really get what is *(char **)bar

edit: worth to mention that bar is declared as const void *bar

3 Answers 3

8
*(char**)bar;

Cast bar to a pointer to pointer to char and dereference, which results in a pointer to char (i.e., a char*).

Remember that pointers are merely indirection. When you dereference a pointer you "drop a star", i.e.:

char ***p = ...;
p    -> char***
*p   -> char**
**p  -> char*
***p -> char
Sign up to request clarification or add additional context in comments.

Comments

3

Beginners and experts alike can benefit from getting the basics really solid.

  • A "variable of type t" is a storage location which can be used to store or fetch a value of type t.
  • A "pointer to t" is a value.
  • Applying the dereferencing operator * to a "pointer to t" produces a "variable of type t".

So what have we got?

void *bar = whatever;
char *foo = *(char **)bar;
  • bar is a variable of type "pointer to void".
  • foo is a variable of type "pointer to char".
  • casting bar to char** reads the variable bar and fetches a value of type "pointer to void". That value is then converted into a value of type "pointer to pointer to char".
  • Dereferencing that value produces a variable of type "pointer to char".
  • The value of that variable is then fetched, and the value is assigned to variable foo.

Make sense?

1 Comment

Yes thanks, bar in this case was of type void* hence the cast to char**
1

I don't know what type bar is without the cast, but here goes:

bar is being cast into a pointer to a pointer to a char.

The * before the (char **) is "dereferencing" the value to its right. In this case, it is returning the char * pointer held in the location pointer to by bar.

The result of the "dereferencing" is a char * -- pointer to a character -- which is assigned to the foo variable of the same type.

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.