2012-10-14 77 views
-1
#include<cstdio> 
#include<iostream> 
#include<cstring> 

using namespace std; 

void f(char **x) 
{ 
    (*x)++; 
    **x = 'a'; 
}  

int main() 
{ 
    char str[]="hello"; 
    f(&str); 
    cout << str << endl; 
    return 0; 
} 

請告訴我爲什麼這個節目是給編譯Error.I現在用的是G ++編譯器編譯錯誤,同時通過雙指針在CPP

Error :temp1.cpp:16:8: error: cannot convert ‘char (*)[6]’ to ‘char**’ for 
     argument ‘1’ to ‘void f(char**)’ 
+2

數組不是指針。你傳遞一個指向數組的指針。 – chris

+0

你忘了在帖子中包含錯誤信息。 –

+0

char * str代替char str,並在f中得到分段錯誤 –

回答

3

陣列可以隱式轉換爲指針,但並不意味着隱含的「指針相當於」已經存在。

您希望f(&str);將隱式創建兩個指針str的指針,該指針。

這個小(工作)的變化說明了這一點:

int main() 
{ 
    char str[]="hello"; 
    char *pstr = str;  // Now the pointer extists... 
    f(&pstr);    // ...and can have an address 
    cout << str << endl; 
    return 0; 
} 
0

你傳入不變焦炭的指針功能,但在函數,你將它作爲指針的指針。那就是問題所在。我在下面評論了問題出在哪裏。 [題外話,但N. B.:數組和指針是不同的概念]

#include<cstdio> 
#include<iostream> 
#include<cstring> 

using namespace std; 

void f(char **x) //**x is pointer of pointer 
{ 
    (*x)++; 
    **x = 'a'; 
}  

int main() 
{ 
    char str[]="hello"; 
    f(&str); //You are passing pointer of constant char. 
    cout << str << endl; 
    return 0; 
} 
0

你會因爲&str&str[0]都與你的函數f碰到一個嚴重的問題評估相同的值...其他海報指出,這些操作指向類型不同,但實際的指針r值將是相同的。因此,在f中,當您嘗試對char**指針進行雙取消引用時,即使您嘗試類似於強制類型的操作來消除類型差異並允許編譯發生錯誤,您也會得到段錯誤。這是因爲你永遠不會得到一個指針指針......事實上,&str&str[0]評估爲相同的指針值意味着一個雙解引用試圖使用str[0]中的char值作爲指針值,它贏得了沒有工作。

0

你的問題是,你將數組視爲指針,當它們不是。數組衰變轉化爲指針,在這種情況下,它不會。當您期望char **時,您傳遞的是char (*)[6]。那些顯然不一樣。

你的參數更改爲char (*x)[6](或使用模板的大小參數):

template <std::size_t N> 
void f(char (*x)[N]) 

一旦進入,你試圖增加什麼X指向。你不能增加一個陣列,所以用一個實際的指針來代替:

char *p = *x; 
p++; 
*p = 'a'; 

都放在一起,(sample

template <std::size_t N> 
void f(char(*x)[N]) 
{ 
    if (N < 2) //so we don't run out of bounds 
     return; 

    char *p = *x; 
    p++; 
    *p = 'a'; 
}