Domanda
Sono nuovo di C89, e non capisco come funzionano le stringhe. Sto sviluppando su Windows 7.
Ecco quello che sto cercando di fare, in Java:
String hostname = url.substring(7, url.indexOf('/'));
Ecco il mio goffo tentativo di fare questo 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
}
Aggiorna per riflettere risposte
Per una hostnameLength
di 14, hostname
è malloc()
'd 31 caratteri. Perché accade questo?
Soluzione
// now what?
è strncpy()
:
hostname = malloc(hostnameLength + 1);
strncpy(hostname, url + 7, hostnameLength);
hostname[hostnameLength] = '\0'; // don't forget to null terminate!
Altri suggerimenti
Dopo di che, è necessario fare:
hostname = malloc(sizeof(char) * (hostnameLength+1));
strncpy(hostname, url + 7, hostnameLength);
hostname[hostnameLength] = 0;
strncpy per i dettagli sulla copia. Si richiede il puntatore destinazione da assegnare in anticipo (da qui il malloc), e sarà solo copiare tanti personaggi ...
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow