C: Trouble with Strings
I am new to C89, and don't really understand how strings work. I am developing on Windows 7.
Here is what I am trying to do, in Java:
String hostname = url.substring(7, url.indexOf('/'));
Here is my clumsy attempt to do this in C89:
// well formed url ensured
void get(char *url) {
int hostnameLength;
char *firstSlash;
char *hostname;
firstSlash = strchr(url + 7, '/');
hostnameLength = strlen(url) - strlen(firstSlash) - 7;
hostname = malloc(sizeof(*hostname) * (hostnameLength + 1));
strncpy(hostname, url + 7, hostnameLength);
hostname[hostnameLength] = 0; // null terminate
}
Update to reflect answers
For a hostnameLength
of 14, hostname
is malloc()
'开发者_如何学编程d 31 characters. Why does this happen?
// now what?
is strncpy()
:
hostname = malloc(hostnameLength + 1);
strncpy(hostname, url + 7, hostnameLength);
hostname[hostnameLength] = '\0'; // don't forget to null terminate!
After that, you need to do:
hostname = malloc(sizeof(char) * (hostnameLength+1));
strncpy(hostname, url + 7, hostnameLength);
hostname[hostnameLength] = 0;
See strncpy for details on the copying. It does require your destination pointer to be allocated in advance (hence the malloc), and will only copy so many characters...
精彩评论