I was trying to solve a coding problem and, to summarize, I was using this piece of code:
char result[50005][26], buffer[50005];
while (fin >> buffer) {
for (int i = 0; i < strlen(buffer); ++i) {
result[lin++][col] = buffer[i];
}
lin = 0;
col++;
}
I needed to read some arbitrary words then store the letters. This worked and gave me 90 points, but it gave a time error. Then I switched the buffer from a char array to an std::string (and the strlen, of course), and it gave me 100 points.
Now I'm left dumbfounded because I can't really seem to grasp the difference between them two. Was reading the char array somehow also "reading" the remaining of the 50k imaginary bytes or something?
strlen(buffer)repeatedly called? Once, before the loop is enough. A lessor compiler may not see that a repeated call is not needed.for (int i = 0; buffer[i]; ++i) { result[lin++][col] = buffer[i]; }would be enough. I think the switch tostd::stringafforded a O(1) time instead ofstrlen()needs O(n).