3

What does the * mean in C? I see it used when declaring a char or FILE variable (char = *test) How does that change how a variable behaves?

Emerald Spire
  • 131
  • 1
  • 10
  • 2
    I don't understand the downvotes. To someone, who is just learning C this is a more relevant question compared to "Pointers in C: when to use ...", because the latter implies, that you already know about pointers. – Lajos Mészáros May 30 '20 at 22:32

2 Answers2

6

It dereferences a pointer:

*ptr = 42; // access the value that ptr points to, and set it to 42

or it declares a pointer:

int* ptr; // the type of ptr is pointer to int
emlai
  • 39,703
  • 9
  • 98
  • 145
  • In the same manner, *p=42; means, that you assign 42 to p, which is wrong if p points to nowhere. – Michi Dec 15 '15 at 15:00
  • 2
    No, `*p = 42` doesn't assign to `p`, it assigns to `*p` (i.e. the thing that `p` points to). And yes, that's undefined behavior if `p` doesn't point to valid memory. – emlai Dec 15 '15 at 15:03
  • Was a typo, I wrote from my phone...I meant *p :) – Michi Dec 15 '15 at 15:06
5

This type of * is called "indirection operator", and *test means "get the data from where the pointer test points".

char is reserved for use as a keyword, so char = *test won't compile unless char is defined as a macro.

Haris
  • 11,989
  • 6
  • 41
  • 67
MikeCAT
  • 69,090
  • 10
  • 44
  • 65