0

I'm learning C and currently, structures. I'm looking at the following code:

struct client {
    char name[20];
    int key;
    int index;
};

struct client Client[100]; 

int function(void *ClientDetail) {
    struct client *clientDetail = (struct client*) ClientDetail; // what is this line doing?
}

could you please explaint the importance of the commented line?

Thanks

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Laura
  • 13
  • 2
  • Importance? Every character is important, except the comments. – i486 May 30 '21 at 20:00
  • Where did you find this code? – klutt May 30 '21 at 20:00
  • @AndreasWenzel Sorry, I tried to post a snippet of code and I made a mistake. Fixed it. – Laura May 30 '21 at 20:00
  • 1
    Note that if the memory pointed to by the `ClientDetail` void pointer isn't actually a `struct client` structure, the code invokes undefined behavior because it violates the [strict aliasing rule](https://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule). It can also invoke undefined behavior because it can violate any alignment restrictions on the system it's running on. Anyone who tells you, "But it works" [left out the "until it doesn't" part](https://stackoverflow.com/questions/46790550/c-undefined-behavior-strict-aliasing-rule-or-incorrect-alignment). – Andrew Henle May 30 '21 at 20:27

2 Answers2

2

This line

struct client *clientDetail = (struct client*) ClientDetail;

reinterprets the address stored in the pointer ClientDetail that has the type void * due to this declaration

int function(void *ClientDetail) {

as an address to an object of the type struct client.

Now using the pointer clientDetail you can access the addressed memory as if there is an object of the type struct client.

Pay attention to that it is a bad idea to use these identifiers ClientDetail and clientDetail that differ only in the case of the first letter.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

The function function takes an argument of type void* and assigns it to a local variable. The type cast (struct client*) is unnecessary and has no effect, as the data type void* can be implicitly converted to any pointer type. Note that this only applies to the programming language C, not C++.

In the posted code, the function argument and the local variable have a very similar name. However, due to C being case-sensitive, the names are considered different by the compiler.

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39