[Solved] Why are old values in an array still present? [closed]


In C, strings are stored as null-terminated arrays of characters. This means that there are many ways to represent the same string: everything in the array of characters after the first null byte is ignored, as far as the value of the string is concerned.

When the first gets call reads HelloWorld, it stores the character 'H' in c[0], 'e' in c[1], …, 'd' in c[9] and 0 (that’s a null byte, not '0') in c[10]. The contents of c[11] through c[1023] are unchanged.

When the second gets call reads Tech, it stores the character 'T' in c[0], 'e' in c[1], 'c' in c[2], 'h' in c[3] and 0 in c[4]. The contents of c[5] through c[1023] are unchanged. In particular, c[5] still has the value W that was set by the first gets call.

If you’re used to high-level languages, you might expect that gets allocates new storage, or that doing what looks like a string access guarantees that you’re actually accessing the string, but neither of these is true.

As you might guess from the fact that you pass an array of characters to gets, it merely writes to that array of characters, it doesn’t allocate new storage. When gets reads a 4-byte string, it writes that 4-byte string plus the terminating null byte, and it doesn’t touch whatever comes after those 5 bytes. In fact, gets doesn’t even know the size of the array (which is why gets is practically unusable in practice and has been removed from the current version of the C language: if you input a line that’s too long for the array, it will overwrite whatever comes after the array in memory).

c[5] accesses the element of the array c at position 5. This happens to be outside the string, but that’s not relevant to how an array access operates. It’s an array access, not a string access. C doesn’t really have strings natively: it fakes them with arrays of characters. String manipulation functions treat their arguments as strings (i.e. they only look up to the first null byte). But an array access is just an array access, and it’s up to the programmer not to access the string, or the array, out of bounds.

solved Why are old values in an array still present? [closed]