2

私は C89 が初めてで、文字列の仕組みがよくわかりません。私はWindows 7で開発しています。

Javaで私がやろうとしていることは次のとおりです。

String hostname = url.substring(7, url.indexOf('/'));

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
}

回答を反映するように更新する

hostnameLength14 のhostname場合、malloc()31 文字です。なぜこれが起こるのですか?

4

2 に答える 2

2

// now what?strncpy():

hostname = malloc(hostnameLength + 1);
strncpy(hostname, url + 7, hostnameLength);
hostname[hostnameLength] = '\0'; // don't forget to null terminate!
于 2010-02-23T01:30:35.713 に答える
0

その後、次のことを行う必要があります。

hostname = malloc(sizeof(char) * (hostnameLength+1));
strncpy(hostname,  url + 7, hostnameLength);
hostname[hostnameLength] = 0;

コピーの詳細については、strncpyを参照してください。宛先ポインターを事前に割り当てる必要があり(したがってmalloc)、非常に多くの文字しかコピーしません...

于 2010-02-23T01:31:14.360 に答える