views:

738

answers:

4

I want to reinitialize d everytime in a loop

     char d[90];   
     while(ptr != NULL)
    {
        printf("Word: %s\n",ptr);
        //int k = 0;
        strcpy(d, ptr);
        d[sizeof(d)-1] = '\0';
        //something more
        ....
        ....
     }
+4  A: 

There's no need to do anything "before" strcpy(). Calling strcpy() on the buffer d will overwrite whatever is in the buffer, and leave the buffer holding the string pointed at by ptr at the time of the call. There's no need for the assignment of the last character to '\0'.

Of course, if you're doing the explicit termination because you're not sure if the strcpy() will overwrite d, then you have a problem. You should use strlen() on ptr before the copy to make sure it fits, or use snprintf() if you have it.

unwind
Great that clears my doubt!! thanks
Alex Xander
@Alex: glad it helped ... And feel free to accept the answer, if you're satisfied.
unwind
strncpy is the safe version of strcpy rather than snprintf
Pete Kirkham
@Pete: I disagree. The semantics of strncpy() are deeply strange, and I consider it best avoided. It has two major faults: it doesn't terminate the output string if the input is larger than the buffer, and it pads the output to its maximum size if the input is smaller. Very rarely what you want.
unwind
A: 

memset(d, 0, 90)?

RC
A: 

unwind is exactly right. You don't need to do anything before strcpy(). However, if you find yourself later needing to initialize some memory to a particular pattern you can use this:

void* pointerToMemory;          // Initialize this appropriately
unsigned char initValue = 0;    // Or whatever 8-bit value you want
size_t numBytesToInitialize;    // Set this appropriately

memset(pointerToMemory, initValue, numBytesToInitialize);
nall
There's also `calloc`.
Tordek
A: 

Simply do strcpy(d, ptr). strcpy will add the NULL terminator at the end for you, of course assuming d can hold at least as many characters as ptr.

Ashwin