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?