用于cout
打印值,例如 cout << *ptr;
int distances[4][6]={{1,0,0,0,1,0},{1,1,0,0,1,1},{1,0,0,0,0,0},{1,1,0,1,0,0}};
int *ptr;
ptr = new int[sizeof(distances[0])];
// sizeof(distances[0]) => 6 elements * Size of int = 6 * 4 = 24 ;
// sizeof(distances) => 24 elements * Size of int = 24 * 4 = 96 ;
// cout << sizeof(distances) << endl << sizeof(distances[0]);
for(int i=0; i<sizeof(distances[0]); i++){
ptr = &distances[0][i];
cout << *ptr << " ";
ptr++;
}
你的代码解释
ptr = distances[i] => ptr = & distances[i][0];
// To put it simple, your assigning address of 1st column of each row
// i = 0 , assigns ptr = distances[0][0] address so o/p 1
// i = 1, assigns ptr = distances[1][0] address so o/p 1
// but when i > 3, i.e i = 4 , your pointing to some memory address because
// your array has only 4 rows and you have exceeded it so resulting in garbage values
我同意@juanchopanza 的解决方案,你的指针大小的计算是错误的
int distances[3][6]={{1,0,0,0,1,0},{1,1,0,0,1,1},{1,0,0,0,0,0}};
// for this case it fails because
// 6 elements * 4 = 24 but total elements are just 18
利用sizeof(distances)/sizeof(int);