I never really was much for pointers and strings...so I don't really see why a declaration like
char *s = "This is a string";
...works...when something like
int *x = 5;
...does not. It has something to do with a pointer to a character being synonymous with an array of characters or something, right? But....a pointer is a variable that points to a memory address...how can it be perfectly legal to point to just an arbitrary string?
Consider this code:
That doesn't really work as planned...in fact, it crashes the program...why is this?Code:#include <iostream> using namespace std; char* Trunc(char* s, int max){ //'max' is 5: so when i=5, make the current character NULL and return the string for(int i=0; i<=max; i++){ if(i==max){ s[i]='\0'; return s; } } } int main(void){ char *m = Trunc("This is a string...",5); cout << m; cin.get(); return 0; }



LinkBack URL
About LinkBacks


