I am working my way through the K&R C programming language and am currently on Chapter 5 (Pointers). I'm having an issue with Exercise 5-3:
"Write a pointer version of the function strcat that we showed in Chapter 2: strcat(s,t) copies string t to the end of s."
I wrote the code below:
#include<stdio.h>
void pointer_strcat(char *stringOne, char *stringTwo);
main(){
char *initialString = "Flash. ";
char *middleString = "Welcome.";
char *addedString = "Thunder.";
pointer_strcat(initialString, addedString);
printf("%s \n", initialString);
}
void pointer_strcat(char *stringOne, char *stringTwo){
while(*stringOne++ != '\0'){
}
*stringOne--;
while( (*stringOne = *stringTwo) != '\0'){
stringOne++;
stringTwo++;
}
}
I tried to follow the examples in the chapter closely but whenever I run this code, there is a freeze and I get a popup that says the .exe stopped working before returning to the command prompt. I messed around with the code every which way and found that if I change the declarations of string pointers to arrays (*initialString becomes initialString[]), everything works exactly how I want it to. I am particularly vexed by this because on page 83, it says:
"As formal parameters in a function definition, char s[]; and char *s; are equivalent;..."
I could really use some advice on why these different declarations have such radically different performance when running the .exe even though both versions compile.