藍森林首頁 | 返回主頁 | 本站地圖 | 站內搜索 | 聯繫信箱 |
 您目前的位置:首頁 > 自由軟件 > 技術交流 > 應用編程


    

藍森林 http://www.lslnet.com 2006年6月6日 10:18


char [] 與 char *

有兩個程序
test1.c 的內容如下:
#include <stdio.h>;
                                                                                                              void pri();
char tmp[] = "hello world";
                                                                                                              int main()
{
        printf("main print tmp:%s\n", tmp);
        pri();
        return 0;
                                                                                                              }

test2.c 的內容如下:
#include <stdio.h>;
                                                                                                             extern char *tmp;
                                                                                                              void pri()
{
        printf("test2.c->;print tmp:%s\n", tmp);
                                                                                                              }

編譯: gcc -g -o test test1.c test2.c
運行:main print tmp:hello world
Segmentation fault

把test2.c 中的extern char *tmp; 改成 extern char tmp[];
一切ok;
為何?

char [] 與 char *

在很多情況下,指針和數組可以互換,但是在這種情況下是特例,是不能互換的,在test2.c中,當pri()讀到tmp時,根據申明是一個指針,所以程序會讀tmp的前四個字節,就是「hell」,這個不是一個地址,所以在運行後出錯

char [] 與 char *

那是不是應該輸出: hell 呢??

char [] 與 char *

我覺得你申請的指針 extern char *temp是個「野指針」,可能會報memery core dump 之類的錯誤提示信息

char [] 與 char *

test2.c 中的tmp為野指針,它的*tmp內容不確定

char [] 與 char *

1月中旬本版win_hate的一篇帖子很好地說明了這個問題,找一下。
看來這個問題還是有很多人碰到的,呵呵。

char [] 與 char *



Copyright © 1999-2000 LSLNET.COM. All rights reserved. 藍森林網站 版權所有。 E-mail : webmaster@lslnet.com