Laura
Laura

Reputation: 13

Writing structures

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

Upvotes: 0

Views: 52

Answers (2)

Andreas Wenzel
Andreas Wenzel

Reputation: 24726

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.

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

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.

Upvotes: 2

Related Questions