#include<iostream>
using namespace std;
void LeftShiftOne(char *s, int n)
{
char t = s[0];
for (int i = 1;i < n;i++)
{
s[i-1] = s[i];
}
s[n - 1] = t;
}
void LeftRotateString(char *s, int n, int m)
{
while (m--)
{
LeftShiftOne(s, n);
}
}
int main()
{
char *s = "abcdef";
int m = 3;
int n = 6;
LeftRotateString(s, n, m);
cout << s << endl;
return 0;
}
執行時出現了異常: 寫入訪問權限沖突
原因是:char s = "abcdef";有問題。將字符指針s指向了一個字符串常量,所以在子函數中不可以通過s來修改字符串常量
可以通過將字符串常量初始化成一個字符數組來解決 :char s[] = "abcdef";因為s[i]不是常量,所以可以通過*str來修改該字符數組,即修改了該字符串。