2012-12-03 68 views
0

是否可以递增传递给函数的数组?递增数组指针

我有一个一维阵列A [4] = {10,20,30,40},我想调用的函数,并且递增所述阵列以指向第三元件和从主打印()。

对于前:

int main() 
{ 
    int a[4] = {10,20,30,40}; 
    cout << *a; // 10 
    increment(); // function call 
    cout << *a; // 40 
} 

我们怎样才能做到这一点。如果数组作为一个指针传递,仅修改存储在阵列的价值得到体现。如果我们必须增加函数中的数组,函数的原型是什么?

+1

有很多关于数组的信息。你尝试了什么? –

+0

查找参考。或者从函数返回一个指针。最后可能是最好的,那么你就不能松原来的“指针”。 –

+0

你是什么意思“增加数组”?数组不是指针。数组是数组。获取指向数组中一个元素的指针并增加_that_。 –

回答

2

替代的建议是:

#include <iostream> 

void foo(int *&p) // <-- take pointer by reference... 
{ 
    ++p; 
    ++p; 
} 

int main(void) 
{ 
    int a[] = {1,2,3,4}; 

    int*p = a; 

    std::cout << *p << std::endl; 

    foo(p); 

    std::cout << *p << std::endl; 

} 

使用第二指针访问原始阵列和修改,在功能...

另外一种选择是使用任一std::vector<int>std::array<int, 4>,然后通过一个迭代器功能(并得到它返回一个迭代器)...

0

不符合您当前的语法。但是,您可以从increment()返回新指针,并将其存储在另一个变量中。

int main() 
{ 
    int a[4] = {10,20,30,40}; 
    cout << *a; 
    int* new_a = increment(a) 
    cout << *new_a; 
} 
0

你可以在你的指针POS接入银行足球比赛这样:

int main() { 
    int a[4] = {10,20,30,40}; 
    cout << *a;  print ---> 10 
    cout << *(a + 3); print ---> 40 
} 

你想要什么你不能没有丢失信息

0

在你的程序分指针在编译时你的程序的数据空间(或链接时间取决于你的想法)。

如果您有类似

void function(int* &x) { 
    x+=2; 
} 

int main() { 
    int *a = new int(4); 
    int *b = a; 
    a[0] = 10; a[1] = 20; a[2] = 30; a[3] = 40; 
    cout << *a; 
    function(b); 
    cout << *b; 
    delete a; 
} 

GNU G ++会检查,而不是让你来移动指针变量,因为没有更多的指针将被引用到这个内存块的头。哈哈