简体   繁体   中英

Why does this function accept a `const char*` as a parameter instead just `char*`?

Noob C questions incoming:

#include <sys/types.h> 
#include <sys/socket.h> 
#include <netdb.h> 
int 
getaddrinfo(const char *hostname, const char *servname, const struct addrinfo *hints, struct addrinfo **res)

void 
freeaddrinfo(struct addrinfo *ai)

Taken from http://www.nxmnpg.com/3/getaddrinfo . Namely I'm interested in why it isn't just getaddrinfo(char *hostname) and is a const instead.

I have an idea what a pointer is. It seems to me that almost all of the functions in C prefer pointers passed to just variables, is this correct?

The const qualifier is a contract the function is making with you ensuring you that it will not change the value of any const arguments passed to it. This can be verified by the compiler so it's a good way to add extra safey and reassurance for you at the end of a long morning (;

C doesn't have the concept of a string as a basic type; it's an array of (char) , which can only be passed to a function as a pointer to (char) . You will also see (long) passed as a pointer in older APIs, dating back to when many of the CPUs on which C was implemented couldn't pass a (long) in a register (thus couldn't be return ed).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM