simran dhamija simran dhamija - 15 days ago 5
C Question

Memset and characters

I aim to copy

dest
string to
source
string. If i compile the following program:

#include <stdio.h>

int main(void) {
char dest[6];
char source[6];

strcpy(dest,source);

while (*dest) { printf("%c",*dest++); }
while (*source) {printf("%c",*source++); }

return 0;
}


I get a runtime error. I suspect it is because
strcpy
copies from source to destination till it encounters
\0
. It did not,however,encounter the null character and kept on copying from the buffer till the runtime error occurred. To solve this problem, i modified the code as follows:

#include <stdio.h>

int main(void) {
char dest[6];
char source[6];


memset(dest, '\0', 6*sizeof(dest)); //trying to set dest to '/0'
strcpy(dest,source);

while (*dest) { printf("%c",*dest++); }
while (*source) {printf("%c",*source++); }

return 0;
}


i get the following errors:


prog.c:11:38: error: lvalue required as increment operand

while (*dest) { printf("%c",*dest++); }
^



and


prog.c:11:38: error: lvalue required as increment operand

while (*dest) { printf("%c",*source++); }
^



Why does this happen?

Answer

For starters it is the source array that shall be zero terminated if you are going to copy it in another character arrays using the standard C function strcpy. So instead of this statement

memset(dest, '\0', 6*sizeof(dest)); 

you should at least write

memset(source, '\0', 6*sizeof(source));
       ^^^^^^                ^^^^^^^

However even this statement is wrong because it overwrites the memory allocated for the array. sizeof( source ) is already equal to 6 bytes as it is followed from the array declaration

char source[6];

Thus you have to write

memset(source, '\0', sizeof(source));
                     ^^^^^^^^^^^^^

In fact there was enough to write either like

char source[6] = { '\0' };

or like

char source[6] = "";

or like

char source[6];
source[0] = '\0';

Arrays are non-modifiable lvalues. Thus you may not write for example the following way

while (*dest) { printf("%c",*dest++); }

Instead of this statement you could write

for ( char *p = dest; *p; ++p ) { printf("%c", *p); }

Take into account that nothing will be outputted because the array contains an empty string. You could initialize the source array with some non-empty string literal.