#include <stdio.h>
#include <string.h>
int main(int argc, const char * argv[]) {
int i;
char s1[100] = "Computer Programming Class";
char s2[100] = "ECE";
int length = (int)strlen(s1);
for (i = 0; i < length; i++) {
s2[i] = s1[length - 1 - i];
}
s2[i] = '\n';
printf("%s", s2);
return 0;
}
This was on one of my tests and I don't understand why it works as intended. It's a piece of code that reverses the order of s1 and stores it in s2 and then prints it out. It appears to me that the null character in s2 would be overwritten when s1 is being stored in it backwards, plus the null character in s1 would never be written in s2 since it's starting from the last character. But it prints out just fine. Why?
strlen
returns the length of the string in characters not including the null terminator, soi < length
does not include the null terminator in its iteration overs1
When you partially initialize an array, as you did with
char s2[100] = "ECE";
the remaining elements are already initialized to zero. In other words, your write tos2
as long aslength < 99
is guaranteed to be null-terminated.