[英]How to clear char array using pointer?
我有一个指向字符数组的字符指针。 我想清除字符数组,然后字符串复制其中的其他数组。memset在char指针上不起作用。 还有其他解决方法吗?
int main(){
char a[100] = "coepismycollege";
char *p;
p = a;
test(p);
printf("After function : %s", a);
}
void test(char *text){
char res[120] = "stackisjustgreat";
printf("text = %s\nres = %s\n", text , res);
memset(&text, 0 , sizeof(*text));
strcpy(text, res);
}
输出应为:stackisjustgreat
提前致谢。
sizeof(*text)
将始终为1(与sizeof(char)
)。 但是,如果您只想将字符串的第一个字节为空就足够了。
memset
的第一个参数是指向内存块开始的指针,而text
已经是指针,因此memset(text, 0 , strlen(text));
是正确的(不带&
)
但是, memset
是没有意义的,因为以下strcopy仍将覆盖它。
您可以像这样更改test()
函数:
void test(char* text) {
char res[120] = "stackisjustgreat";
const size_t len = strlen(res); // NOT sizeof(res)
memset(text, 0, len); // This is actually not necesary!
strncpy(text, res, len); // text will already be properly null-terminated
}
甚至更短的版本可能是:
void test(char* test) {
char res[120] = "stackisjustgreat";
strcpy(test, res, strlen(res));
}
只需通过strlen(res)
找出res
指向的字符串的长度,然后使用str(n)cpy()
复制该字符串即可。 由于str(n)cpy()
复制空字符,因此无需执行其他操作。
在memset的一行上,参数1应该只是text,text已经是一个指针。 放置&text将把指针指向该指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.