由char *str与char str[]引发的思索

昨天写一个字符串逆置的程序,开始是这么写的:

#include <iostream>
using namespace std;

char* ReverseWord(char* val);

int main()
{
char *str="hello";

cout<<ReverseWord(str);

return 0;
}

char* ReverseWord(char* val)
{
char* right=val+strlen(val)-1;
char* left=val;

//r* right=val;
//while(*right != '\0')
//{
// right++;
//}
//right--;
//char* temp='a';

while(right > left)
{
*left=*left^*right;
*right=*left^*right;
*left=*left++^*right--;
}

return val;
}

运行结果:程序编译通过,但运行崩溃

我通过调试,在*left=*left^*right;这句的时候不能调试进去了,出现了下面的情况:

调试过程如下面这篇般难搞:http://hi.baidu.com/%C2%ED%D0%C2%CC%CE/blog/item/393421acbfe3b2034b36d6bc.html

虽然调试看了汇编代码,但还是搞不清楚问题在哪里。后面干脆发了贴,得到了正确答案,哎,谁知问题就在眼皮底下,遇到BUG不要慌啊!

#include <iostream>
using namespace std;

char* ReverseWord(char* val);

int main()
{
char str[]="hello";

cout<<ReverseWord(str)<<endl;

return 0;
}

char* ReverseWord(char* val)
{
char* right=val+strlen(val)-1;
char* left=val;

//r* right=val;
//while(*right != '\0')
//{
// right++;
//}
//right--;
//char* temp='a';

while(right > left)
{
*left=*left^*right;
*right=*left^*right;
*left=*left++^*right--;
}

return val;
}

运行结果:olleh

问题的解决紧紧是:将char *str改为了char str[],其实当问题解决了,也就知道为什么要将将char *str改为char str[]。

所以下面来说说char *str与char str[]的区别:

其实我以前一篇文章,可以说已经讲到了。http://www.cnblogs.com/chenyuming507950417/archive/2011/12/29/2306043.html

还是搜搜网上专家人士的权威理解吧。

(1)The two declarations are not the same.

char ptr[] = "string"; declares a char array of size 7 and initializes it with the characters
s ,t,r,i,n,g and \0. You are allowed to modify the contents of this array.

char *ptr = "string"; declares ptr as a char pointer and initializes it with address of string literal"string" which is read-only. Modifying a string literal is an undefined behavior. What you saw(seg fault) is one manifestation of the undefined behavior.

(2)char *test = "string test"; is wrong, it should have been const char*. This code compiles just because of backward comptability reasons. The memory pointed by const char* is a read-only memory and whenever you try to write to it, it will invoke undefined behavior. On the other hand char test[] = "string test" creates a writable character array on stack. This like any other regualr local variable to which you can write.

看了上面两条,其它无非都是些讲指针与数组的问题了。

原帖:(1)http://topic.csdn.net/u/20120404/20/5ed24daa-6a18-41b0-be25-7df249061976.html

        (2)http://topic.csdn.net/u/20120404/19/b0d265db-5f5f-460d-88d4-0f3471a08e8b.html

参考文献:

(1)http://stackoverflow.com/questions/3862842/difference-between-char-str-string-and-char-str-string

(2)http://hi.baidu.com/%C2%ED%D0%C2%CC%CE/blog/item/393421acbfe3b2034b36d6bc.html

(3)http://blog.csdn.net/lzpaul/article/details/2884095

(4)http://dmacy.bokee.com/4728674.html

(5)http://www.cnblogs.com/octobershiner/archive/2012/04/03/2431544.html#2347328  (字符串的逆序之旅)
(6)陈皓:http://blog.csdn.net/haoel/article/details/1395358

 

原文地址:https://www.cnblogs.com/danshui/p/2432704.html