Reputation: 89
Disclaimer: The code below is taken from Derek Banas off youtube, I just don't understand why it works.
In the code below the entire string is changed even though the string isn't the same size. I do not understand how the entire string is changed when the for loop does not go through all the indexes however. For example, if oldString was of length 10, and newString was of size 5, the for loop below would change indexes 0 to 4 on oldString (as far as I can tell,) but the rest of the String is somehow deleted and I am not sure how. I have tested the code myself and it does work.
#include <string.h>
#include <stdio.h>
void editMessageSent(char* message, int size){
char newMessage[] = "New Message";
if(size > sizeof(newMessage)){
for(int i = 0; i < sizeof(newMessage); i++){
message[i] = newMessage[i];
}
} else {
printf("New Message is too big\n\n");
}
}
void main(){
// Passing a String to a Function ----
char randomMessage[] = "Edit my function";
printf("Old Message: %s \n\n",
randomMessage);
editMessageSent(randomMessage,
sizeof(randomMessage));
printf("New Message: %s \n\n",
randomMessage);
}
Upvotes: 0
Views: 49
Reputation: 122383
If the new string is shorter, the null terminater '\0'
is copied into the old string as well.
And after editMessageSent
, for example, if the new string is "hello"
:
"Edit my function" -> "hello\0y function"
"%s"
in printf
outputs the string until the first '\0'
.
Upvotes: 2