2014-05-24 61 views
-3

讓我舉一個例子就明白了我的問題:指針在主函數中的修改而不指針

void fct1() 
{ 
int T[20]; 
int* p=T;//the goal is to modify this pointer (p) 
fct2(&p); 
} 
void fct2(int** p) 
{ 
    (*p)++;//this will increment the value of the original p in the fct1 
} 

我要的是避免指針和只引用做到這一點,這是可能的?

+8

您*嘗試*使用參考?什麼地方出了錯? (另外,請不要在[C]中標記有關引用的問題。在C中沒有引用) –

+0

我正在使用visual C++,並且想使用引用,但我不知道如何? –

回答

1

使用引用是的,是可以做到的。

void fct2(int* &p) { 
    p++; 
} 
+0

這也會增加原始指針 – 4pie0

+1

是的。 OP想要那個。 –

+0

即使這是指針和參考不僅參考 – 4pie0

0

我會建議使用,如果可以通過std::array提供的迭代器:

void fct1() 
{ 
    std::array<int, 20> l; 
    auto it = l.begin(); 
    fct2(it); 
} 

template<class I> 
void fct2(I& it) 
{ 
    ++it; 
}