我有
char filemem[14], *file, *path;
file = strcpy(filemem,"/path/to/file");
path = file - 4;
我想要char *path = file - 4
这样的char *path
只读取/path/to/
. 是否可以显示指针的一部分而不必将字符串的副本创建到另一个内存中
在 C 中,字符串总是以 NUL 字节 ( '\0'
)结尾。
char *path = file - 4
将指向file
指针前面四个字节的地址。这并不意味着“将字符串截断四个字节”。
为了截断一个字符串,你必须在你想要的最后一个字符后面放置一个 NUL 字节。如果您的字符串是只读的,您必须有额外的内存来复制所需的字符。没有办法让 C 字符串的切片在 NUL 终止字节之前结束,并且仍然对期望 NUL 终止字符串的函数有效。
一些例子:
修改现有字符串:
int main(void) {
char file[] = "/path/to/file";
strrchr(file, '/')[1] = '\0';
puts(file);
}
从只读内存中复制子字符串:
char *repath(const char *path) {
size_t len = strrchr(path, '/') - path + 1;
return strncpy(calloc(len + 1, 1), path, len);
}
int main(void) {
const char *file = "/path/to/file";
char *fileless = repath(file);
puts(fileless);
free(fileless);
}
(为简洁起见,两个示例中都省略了错误处理。strrchr
并且calloc
可以返回 NULL。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句