const char* occurs(const char* s1, const char* st){
if(length(st)>length(s1)){
return 0;
}
int diff=length(s1)-length(st);
int i=0, j=0, k=0;
for(;i<=diff;i++){
j=i;
while(s1[j]==st[k] && st[k]!='\0'){
k++;
j++;
}
if(st[k]=='\0') return &s1[i];
}
return 0;
}
This function returns the first occurrence of a string in another string. In my main function, I call it like this:
const char* occ = occurs(argv[1], argv[2]);
std::cout << &occ << " - " << occ << std::endl;
What confuses me is: being occ a pointer, shouldn't I get the address by writing the variable as is (occ) and the value by dereferencing it (*occ)? Why does it seem to be working like a normal variable (Getting the address with &occ and the value with occ)? Does C++ change something about a pointer if I treat it like an array? If I solved the problem by considering s1 and st as pointers, without using the array semantic, would it have been the same in regards to the memory?
<<has a special overload forconst char*to print a c-style string.lengthagain and again is not a good idea. Better usestr::string<<. Also, I know it's not a good idea, it's just an exercise to understand better pointers/arrays (so not usingstr::string) and I didn't bother saving the lengths in different variables, ahah.