tags:

views:

118

answers:

5
+4  A: 

for(int i=0;str[i]!='\0';i++,strcpy(&str[i],"\0")); - the i++ is incrementing i before the strcpy executes - so it'll be taking the address of str[1] on the first iteration - skipping over str[0] - hence you'll get the first character.

Note that KennyTM's response is a far better way of doing this - but I guess you're learning / experimenting.

Will A
I read that the expressions proceeds from right to left.strcpy() should proceed frist then?
fahad
If you want to use this approach then yes, strcpy should be on the left hand side of the comma - the items are executed left-to-right.
Will A
I said that they proceed from left to right i.e strcpy in this example should be performed first and then i++
fahad
+3  A: 

Because i++,strcpy(&str[i],"\0") evaluates the i++ before it evaluates the call to strcpy() which uses the now incremented value of i as its destination. In effect, it skips the first character of your string.

Note that there are much better ways to do what you want.

KennyTM mentioned just setting the first character to '\0' with str[0] = '\0';, which doesn't clear every byte but does mark the string as having zero length.

There is also memset() which is used to fill a block of memory with any arbitrary value, and 0 is certainly allowed.

Furthermore, calling strcpy() is far less efficient that just assigning to each element of str[] in the loop.

RBerteig
A: 

Try with this code:

bzero(string_name, size_of_string);

Also, include the <string.h> lib file. I think this must work.

Khushboo
`bzero` is a legacy BSD function that duplicates the standard C `memset`. It shouldn't be recommended for new code.
R..
+7  A: 
memset(str,0,strlen(str)); /* should also work */
memset(str,0,sizeof str); /* initialize the entire content */
+4  A: 

C strings are null-terminated. As long as you only use the functions assuming null-terminated strings, you could just zero the first character.

str[0] = '\0';
KennyTM