2
int** mat = new int*[5];

// define the elements to be inserted to the matrix     
int* i1 = new int;
*i1 = 1;

int* i2 = new int;
*i2 = 2;

int* i3 = new int;
*i3 = 3;

int* i4 = new int;
*i4 = 4;

int* i5 = new int;
*i5 = 5;

// insert the elements to the matrix
mat[0] = i1;
mat[1] = i2;
mat[2] = i3;
mat[3] = i4;
mat[4] = i5;

now I define the pointer. I want to print the matrix through this pointer. so I define it:

int* ptr = *mat;

and here I print it:

for (int i = 0; i < 5; i++) {
    cout << *ptr << endl;
    ptr++;
}

but I got:

1
2543679
9826
257678
7853

please remember that I want to print it through a pointer (and do it ++) so relate only to the definition of the ptr and the for loop

4

1 回答 1

4
int* ptr = *mat;

在这里等价于

int *ptr = i1;

所以你让ptr指向同一个地方i1。然后递增ptr使其指向intwhere 点后面的i1点。您还没有在那里分配(和填充)内存,因此取消引用递增的指针会调用未定义的行为(并且递增它会进一步调用未定义的行为,即使没有取消引用)。

要在阵列中移动,您需要

int **ptr = mat;
for (int i = 0; i < 5; i++) {
    cout << **ptr << endl;
    ptr++;
}

(但使用下标

for(int i = 0; i < 5; ++i) {
    cout << *mat[i] << endl;
}

会更具可读性)

于 2013-05-25T10:26:16.050 回答