如何使用指针清除char数组?

时间:2017-09-10 03:16:00

标签: c arrays pointers character

我有一个指向字符数组的字符指针。 我想清除字符数组然后字符串复制其中的一些其他数组.memset不能处理字符指针。 还有其他方法可以做到这一点吗?

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
提前致谢。

3 个答案:

答案 0 :(得分:1)

sizeof(*text)将始终为1(与sizeof(char)相同)。但是,如果你打算只使字符串的第一个字节为空,那就足够了。

memset的第一个参数是指向内存块开始的指针,text已经是指针,所以memset(text, 0 , strlen(text));是正确的(没有&

然而,memset毫无意义,因为下面的strcopy无论如何都会覆盖它。

答案 1 :(得分:1)

您可以像这样更改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));
}

找出res指向strlen(res)的字符串的长度,然后使用str(n)cpy()复制字符串。因为str(n)cpy()也复制了空字符,所以没有必要再做了。

答案 2 :(得分:0)

在memset的行上,参数1应该只是文本,文本已经是指针。 Putting& text将指向该指针。