如何使用指针将数组复制到内存中的其他位置

时间:2013-11-03 09:22:23

标签: c++

我是c ++编程的全新人物。我想将名为distance的数组复制到指针指向的位置,然后我想打印出结果,看它是否有效。

这就是我所做的:

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++;
}

我不知道如何打印指针的内容以查看其工作原理。

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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);