[英]How to clear char array using pointer?
I have a character pointer which points to the character array. 我有一个指向字符数组的字符指针。 I want to clear the character array and then string copy some other array in it.The memset doesn't work on char pointer.
我想清除字符数组,然后字符串复制其中的其他数组。memset在char指针上不起作用。 Is there some other way around to do that ?
还有其他解决方法吗?
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);
}
output should be : stackisjustgreat 输出应为:stackisjustgreat
Thanks in advance. 提前致谢。
sizeof(*text)
will always be 1 (it is same as to sizeof(char)
). sizeof(*text)
将始终为1(与sizeof(char)
)。 It is, however, sufficient, if you intended to null only the first byte of string. 但是,如果您只想将字符串的第一个字节为空就足够了。
memset
's first argument is pointer to start of memory block, and text
is already a pointer, so memset(text, 0 , strlen(text));
memset
的第一个参数是指向内存块开始的指针,而text
已经是指针,因此memset(text, 0 , strlen(text));
is correct (without the &
) 是正确的(不带
&
)
However, memset
is pointless, as the following strcopy will overwrite it anyway. 但是,
memset
是没有意义的,因为以下strcopy仍将覆盖它。
You can change test()
function like this: 您可以像这样更改
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
}
Even shorter version could be: 甚至更短的版本可能是:
void test(char* test) {
char res[120] = "stackisjustgreat";
strcpy(test, res, strlen(res));
}
Just find out the length of the string to which res
points by strlen(res)
and then use str(n)cpy()
to copy the string. 只需通过
strlen(res)
找出res
指向的字符串的长度,然后使用str(n)cpy()
复制该字符串即可。 Because str(n)cpy()
copy the null character as well, there is no more necessary to be done. 由于
str(n)cpy()
复制空字符,因此无需执行其他操作。
On the line with the memset, argument 1 should simply be text, text is already a pointer. 在memset的一行上,参数1应该只是text,text已经是一个指针。 Putting &text will put a pointer to that pointer.
放置&text将把指针指向该指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.