0

我是 C++ 编程的新手。我想将名为 distances 的数组复制到指针指向的位置,然后我想打印出结果以查看它是否有效。

这就是我所做的:

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])];
for(int i=0; i<sizeof(distances[0]); i++){
   ptr=distances[i];
   ptr++;
}

我不知道如何打印出指针的内容,看看它是如何工作的。

4

2 回答 2

2

首先,你的ptr数组的大小计算是错误的。它似乎只起作用,因为int您平台上的大小是4,这也是数组中的维度之一。获得正确尺寸的一种方法是

 size_t len = sizeof(distances)/sizeof(int);

然后你可以实例化你的数组并std::copy用来复制元素:

int* ptr  = new int[len];
int* start = &dist[0][0];
std::copy(start, start + len, ptr);

最后,将它们打印出来:

for (size_t i = 0; i < len; ++i)
  std::cout << ptr[i] << " ";
std::cout << std::endl;

....
delete [] ptr; // don't forget to delete what you new

请注意,对于实际应用程序,您应该更喜欢使用std::vector<int>手动管理的动态分配数组:

// instantiates vector with copy of data
std::vector<int> data(start, start + len);

// print 
for (i : data)
  std::cout << i << " ";
std::cout << std::endl;
于 2013-11-03T09:45:06.113 回答
0

用于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);

于 2013-11-03T09:26:02.873 回答