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
}

更新以反映答案

对于 ahostnameLength的 14,hostnamemalloc()'d 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 回答