char *p = "abc"; // 指標宣告, "abc"這個陣列會放在記憶體的"常數區塊",不允許被修改
char q[] = {'a','b','c',0}; // 陣列宣告,同時給予初始值
char r[] = "abc"; // 陣列宣告, 此空間就放在堆疊上
q[0] = '!'; // q字串變成 "!bc"
r[0] = '!'; // r字串變成 "!bc"
*p = '!'; // 這在Unix系統上會造成Segmentation fault (core dumped)
#include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;
char * strcopy(char *dest, char *from)
{
char *p = dest;
while(*dest++ = *from++)
;
return p;
}
char * strconcat(char *dest, char *from)
{
char *p = dest;
while(*dest) dest++;
while(*dest++ = *from++)
;
return p;
}
char * strrever(char *dest)
{
char *p = dest;
char *pt = dest;
while(*dest) dest++;
;
for(--dest; pt < dest; pt++, dest--)
{
*pt = *pt ^ *dest;
*dest = *pt ^ *dest;
*pt = *pt ^ *dest;
}
return p;
}
int main()
{
//char str1[]="123 "; // dest須給足空間 否則會有問題
//char *str1 = "123456789" // error 指標已指定長數空間 不能更改其內容
char *str1 = (char *)malloc(20); // dest須給足空間 否則會有問題
char *str2="abcdef";
char *str3 = strcopy(str1, str2);
cout << str1 <<endl;
cout << str2 <<endl;
cout << str3 <<endl;
//strcat(str1, str2);
char *str4 = strconcat(str1, "test");
cout << str1 <<endl;
cout << str2 <<endl;
cout << str4 <<endl;
char *str5 = strrever(str1);
cout << str1 <<endl;
cout << str2 <<endl;
cout << str5 <<endl;
return 0;
}