Segmentation Fault using double pointers

时间:2018-12-03 13:02:51

标签: c++ segmentation-fault

I'm getting segmentation fault while handling with double pointer in the below code. I've spent way too much time and couldn't find what the error was.

#include<iostream>
using namespace std;
int main(){
    int *p,**pp,n=2;
    p=new int;
    pp=&p;

    for(int i=0;i<n;i++)
    {
        cin>>*(*(pp+i))>>*(*(pp+i)+1);
    }
    for(int i=0;i<n;i++)
    {
        cout<<*(*(pp+i))<<" "<<*(*(pp+i)+1)<<endl;
    }
    return 0;
}

Not sure if this is a noob question.

1 个答案:

答案 0 :(得分:0)

Maybe this is what you need:

int *p, **pp, n = 2;
p = new int[n * 2];
pp = &p;

for(int i = 0;i < n;i++)
    cin >> *(*pp + n*i + i) >> *(*pp + n*i + i + 1);
for(int i = 0;i < n;i++)
    cout << *(*pp + n*i + i) << " " << *(*pp + n*i + i + 1) << endl;

delete []p;
return 0;