Reputation: 159
I am completely new in c++ programming. I want to copy the array called distances into where pointer is pointing to and then I want to print out the resul to see if it is worked or not.
this is what I have done:
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++;
}
I do not know how to print out the contents of the pointer to see how it works.
Upvotes: 0
Views: 115
Reputation: 9393
use cout
to print values like 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++;
}
Explaination of your code
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
I agree with @juanchopanza solution, calculation of your pointer size is wrong
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
Use sizeof(distances)/sizeof(int);
Upvotes: 0
Reputation: 227418
First of all, the size calculation of your ptr
array is wrong. It only seems to work because the size of an int
on your platform is 4
, which is also one of the dimensions in your array. One way to get the right size is
size_t len = sizeof(distances)/sizeof(int);
Then you can instantiate your array and use std::copy
to copy the elements:
int* ptr = new int[len];
int* start = &dist[0][0];
std::copy(start, start + len, ptr);
Finally, print them out:
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
Note that for a real application you should favour using std::vector<int>
over a manually managed dynamically allocated array:
// instantiates vector with copy of data
std::vector<int> data(start, start + len);
// print
for (i : data)
std::cout << i << " ";
std::cout << std::endl;
Upvotes: 2