I'm starting with sockets on Windows in C, and I'm trying to understand the use of pointers in C and get a clear idea of why some variables are pointers.
In this code:
int sock;
struct sockaddr_in ServAddr;
unsigned short ServPort;
char *ServIP;
WSADATA wsaData;
ServIP = "192.168.1.6";
ServPort = 50005;
if (WSAStartup(MAKEWORD(2,0), &wsaData) != 0) {
exit(1);
}
sock = socket(AF_INET, SOCK_STREAM, 0);
memset(&ServAddr, 0, sizeof(ServAddr));
ServAddr.sin_family = AF_INET;
ServAddr.sin_addr.s_addr = inet_addr(ServIP);
ServAddr.sin_port = htons(ServPort);
1. Why is ServIP a pointer and ServPort is not?
unsigned short ServPort;
char *ServIP;`
ServIP = "192.168.1.6";
ServPort = 50005;
2. Are these variables pointers?
struct sockaddr_in ServAddr;
WSADATA wsaData;
ServIPis achar *because that's the type that substantially all C functions require for handling strings. The value is actually a pointer to the firstcharof the string, which continues up to and including the firstcharwith value 0.ServPortis not a pointer because there is no reason for it to be one.unsigned shortis the type required for this variable's purpose.The question makes me wonder whether you are among those who take pointer-ness to be analogous to a type qualifier, such as
const, that produces a different variant of a base type. This is not the case at all. Pointer types are completely separate types from their pointed-to types. They generally have different size and representation, and are in no way interchangeable with their pointed-to type.* Thus, you use pointers for things that require pointers and not for things that require non-pointers.struct sockaddr_inis definitely a structure type, not a pointer type. We know this from the presence of thestructkeyword and the absence of*from the type name, together.ServAddrtherefore is not a pointer.It is not immediately apparent from the name
WSADATAwhether that is a pointer type. It is a macro or typedef name that obscures the details (in fact the latter). But if we look it up, we can find its documentation pretty easily, and that reveals thatWSADATAis a structure type, not a pointer type. SowsaDatais not a pointer.* With some exceptions related to type
void *, which I'm glossing over for the sake of simplicity.