Below are two chunks of code, and I am not able to figure out why is the output in the following way. In the first code, I use printf to print the returned pointer, so it works right in the main function too, but in the second when I remove the printf statement, it prints something else. And the output changes everytime.
The main function is same for both the cases.
char * updateSlidingWindow(char * slide, char newChar) {
char * c, dst[strlen(slide)];
int dstindex = 0;
c = slide + 1;
while(*c != '\0')
dst[dstindex++] = (char)*c++;
dst[dstindex++] = newChar;
dst[dstindex] = '\0';
slide = dst;
printf("%s\n", slide); // This line is commented for testing. It changes output.
return slide;
}
// main function
int main(void) {
char * SLIDING_WINDOW = "Hello";
SLIDING_WINDOW = updateSlidingWindow(SLIDING_WINDOW, 'D');
printf("%s\n", SLIDING_WINDOW);
return 0;
}
Output - With printf in update function -
elloD
elloD
Without printf in update function -
����