Domanda

I'm learning C++ through online tutorials such as the one at cprogramming.com, and have decided to create a simple socket program as my first real project. I have already experimented with basic functions and get the gist of how C++ works. I just ran into something on the MSDN Winsock2 walk-through that confused me.

On this page, an object named hints is declared from the sddrinfo structure:

struct addrinfo *result = NULL,
                *ptr = NULL,
                hints;

I am confused about the *result and *ptr = null parts of this declaration. Since there are no semicolons i assume the newlines are for readability purposes and this code can be written like this.

struct addrinfo *result = NULL, *ptr = NULL, hints;

It appears that we are declaring two pointers that point to the addrinfo struct and setting them to null along with declaring a hints object. Can someone explain the purpose of setting these to NULL? And if anyone is familiar with winsock can you explain how and why these pointers are used? Why not just use the hints object?

È stato utile?

Soluzione

That line declares multiple variables in one line. It's the same thing as this

struct addrinfo *result = NULL;
struct addrinfo *ptr = NULL;
struct addrinfo hints;

Programmers set pointers to NULL so that if you accidentally dereference them, you'll throw an exception and find your error. If you don't initialize them, they'll point to junk which can cause your application to crash in devious manners.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top