C:字符串问题
我是 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
}
更新以反映答案
对于 hostnameLength
共 14 个,hostname
是 malloc()
'd 31 个字符。为什么会出现这种情况?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
// 现在怎么办?
是strncpy()
:// now what?
isstrncpy()
:之后,您需要执行以下操作:
有关复制的详细信息,请参阅 strncpy。它确实需要提前分配目标指针(因此是 malloc),并且只会复制这么多字符......
After that, you need to do:
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...