Savan
Savan

Reputation: 171

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. 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
Thanks in advance.

Upvotes: 0

Views: 2743

Answers (3)

sizeof(*text) will always be 1 (it is same as to 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)); is correct (without the &)

However, memset is pointless, as the following strcopy will overwrite it anyway.

Upvotes: 1

Miroslav Mares
Miroslav Mares

Reputation: 2392

You can change test() function like this:

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. Because str(n)cpy() copy the null character as well, there is no more necessary to be done.

Upvotes: 1

Hallowizer
Hallowizer

Reputation: 56

On the line with the memset, argument 1 should simply be text, text is already a pointer. Putting &text will put a pointer to that pointer.

Upvotes: 0

Related Questions