一
#include <bits/stdc++.h> using namespace std; void f(char *str) { char *s = str; str[0] = '0' //error str是指向常量的指针,只能读取不能修改,如果str是malloc过则可以修改 s[1] = '1'; //同上error cout<<s<<endl; } int main() { char *s = "We Are Happy."; f(s); puts(s); return 0; }
二
#include <bits/stdc++.h> using namespace std; void f(char *str) { char *s = str; s[0] = 'a', s[1] = 'b', s[2] = 'c', s[3] = '\0'; str = s; } int main() { char s[] = "We Are Happy."; f(s); puts(s); //abc return 0; }
三
#include <bits/stdc++.h> using namespace std; void f(char *str) { char *s = (char *)malloc(sizeof(char)*100); s[0] = 'a', s[1] = 'b', s[2] = 'c', s[3] = '\0'; str = s; } int main() { char s[] = "We Are Happy."; f(s); puts(s); //We Are Happy. return 0; }
四
#include <bits/stdc++.h> using namespace std; void f(char *str) { char *s = (char *)malloc(sizeof(char)*100); s[0] = 'a', s[1] = 'b', s[2] = 'c', s[3] = '\0'; strcpy(str, s); } int main() { char s[] = "We Are Happy."; f(s); puts(s); //abc return 0; }