2

What is happening when i write array[i] = '\0' inside a for loop?

char arrayPin[256];

for(int i = 0; i<256; i++) 
{ 
    arrayPin[i] = '\0'; 
}
1
  • 4
    Another way to do the same in this particular case is memset(arrayPin, 0, 256); Commented Apr 12, 2011 at 0:32

3 Answers 3

2

The program attempts to access memory at the location of <base address of 'array'> + (<sizeof array element> * 'i') and assign the value 0 to it (binary 0, not character '0'). This operation may or may not succeed, and may even crash the application, depending upon the state of 'array' and 'i'.

If your array is of type char* or char[] and the assignment operation succeeds, then inserting the binary 0 at position 'i' will truncate the string at that position when it is used with things that understand C-style strings (printf() being one example).

So if you do this in a for loop across the entire length of the string, you will wipe out any existing data in the string and cause it to be interpreted as an empty/zero-length string by things that process C-style strings.

Sign up to request clarification or add additional context in comments.

Comments

1
char arrayPin[256];

After the line above, arrayPin in an uninitialized array whose contents are unknown (assuming it is not a global).

     ----------------------------
     |?|?|?|?|?|?|?|?|?|?|...|? |
     ----------------------------
byte: 0 1 2 3 4 5 6 7 8 9     255

Following code:

for(int i = 0; i<256; i++) 
{ 
    arrayPin[i] = '\0'; 
}

initializes every arrayPin element to 0:

     ----------------------------
     |0|0|0|0|0|0|0|0|0|0|...|0 |
     ----------------------------
byte: 0 1 2 3 4 5 6 7 8 9     255

Comments

0

I suppose you have something like char *array. In this case It will write character with the code 0x00 into ith position.

This is quite useful when you work with ANSI strings. \0 indicates the end of the string. For example:

char str[] = "Hello world";
cout << str << endl; // Output "Hello world"
str[5] = '\0';
cout << str << endl; // Output just "Hello"

1 Comment

Modifying the contents of a string literal is actually undefined behaviour. Use char str[] = "Hello world"; if you want to modify the string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.