I just started using c ++. I am trying to run a forward Euler, where I use a for loop and pointers. But I don't understand what's wrong?
#include <iostream>
using namespace std;
void euler(){
int n = 10;
double dt = 0.1;
double *a=new double[n];
double *v=new double[n];
double *t = new double[n];
int vr = 5;
for (int i=0;i<n; i++){
a[i+1] = vr + i;
v[i+1] = v[i] + a[i+1]*dt;
t[i+1] = t[i] + dt;
}
cout << v << endl;
}
int main(int argc, char const *argv[]) {
euler();
return 0;
}
The terminal gives me this "0x7fce7cc017d0"
You are printing out the pointer itself, instead of the value to which it is pointing. Try one of these:
cout << *v << endl;
or
for (int i=0;i<n; i++)
cout << v[i] << endl;
Also, as mentioned in a commment, no need for the +1 in your array indexing. By the way, this is not a good use of pointers in C++. In general, you don't want to use pointers unless you really need to. With code as simple as yours, you can simply declare arrays.
double *v=new double[n];
...
cout << v << endl;
V is a pointer to an array of n doubles.
When you are printing you are printing the value of the pointer.
Which is why you get results like "0x7fce7cc017d0" because that's the value of the pointer.
If you want to print out the values of the array you must index into it properly.
std::cout << v[0] << "\n"
You can make your original code print the content of vector v if you implement operator << for vecotor, for example like here:
Overloading output stream operator for vector<T>
Related
I am trying to write a function that swap two arrays in O(1) time complexity. However, when i try to write the function parameters, I get the error:
error: cannot convert ‘int (*)[4]’ to ‘int**’
Here is my code:
#include <iostream>
using namespace std;
void swap_array_by_ptr(int* a[], int* b[]) {
int* temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int fr[] = {1,2,3,4};
int rv[] = {4,3,2,1};
swap_array_by_ptr(&fr, &rv);
for (int i = 0; i < 4 ; i++) {
cout << fr[i] << " ";
}
cout << endl;
for (int i = 0; i < 4 ; i++) {
cout << rv[i] << " ";
}
}
However, when i tried to define the arrays with 'new' command, this works as expected as below:
#include <iostream>
using namespace std;
void swap_array_by_ptr(int** a, int** b) {
int* temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int fr = new int[4]{1,2,3,4};
int rv = new int[4]{4,3,2,1};
swap_array_by_ptr(&fr, &rv);
for (int i = 0; i < 4 ; i++) {
cout << fr[i] << " ";
}
cout << endl;
for (int i = 0; i < 4 ; i++) {
cout << rv[i] << " ";
}
}
Is there any way that i can define the arrays with [] method and swap the arrays by sending these arrays with '&array' method ?
As I believe, there must be a way to do that, I only achieve this when I'm trying to do with 'new' method. However, is there any way to swap two arrays in O(1) complexity with sending parameters as
swap_array_by_ptr(&fr, &rv);
?
Thanks for help.
You can not swap two arrays with O( 1 ). You need to swap each pairs of corresponding elements of two arrays.
In the first program
int fr[] = {1,2,3,4};
int rv[] = {4,3,2,1};
swap_array_by_ptr(&fr, &rv);
the expressions &fr and &rv have type int( * )[4] while the corresponding function parameters in fact has the type int **
void swap_array_by_ptr(int* a[], int* b[]) {
after adjusting the parameters having array types to pointers to the array element types by the compiler.
So the compiler issues an error.
You could use standard function std::swap declared in the header <utility> the following way
std::swap( fr, rv );
But in any case its complexity is O( n ).
In the second program there are at least typos. Instead of
int fr = new int[4]{1,2,3,4};
int rv = new int[4]{4,3,2,1};
you have to write
int *fr = new int[4]{1,2,3,4};
int *rv = new int[4]{4,3,2,1};
In this case you are not swapping arrays themselves. That is the arrays will still store their initial values. You are swapping pointers that point to the dynamically allocated arrays.
To be sure that arrays are not swapped consider the following demonstration program.
#include <iostream>
using namespace std;
void swap_array_by_ptr(int** a, int** b) {
int* temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int fr[] = { 1,2,3,4};
int rv[] = {4,3,2,1};
int *p1 = fr;
int *p2 = rv;
swap_array_by_ptr( &p1, &p2 );
for (int i = 0; i < 4 ; i++) {
cout << p1[i] << " ";
}
cout << endl;
for (int i = 0; i < 4 ; i++) {
cout << p2[i] << " ";
}
cout << endl;
for (int i = 0; i < 4 ; i++) {
cout << fr[i] << " ";
}
cout << endl;
for (int i = 0; i < 4 ; i++) {
cout << rv[i] << " ";
}
cout << endl;
}
It is a syntactic quirk inherited from C that a declaration of a function parameter as an array is automatically converted to a declaration as a corresponding pointer. This is not as odd as it might first seem, however, because it dovetails with the automatic conversion of function arguments of array type to corresponding pointers, also inherited from C.*
Thus, this declaration ...
void swap_array_by_ptr(int* a[], int* b[]) {
... is equivalent to this one:
void swap_array_by_ptr(int **a, int **b) {
. But the arguments you are passing do not match. This, for example,
int fr[] = {1,2,3,4};
declares fr as an array of 4 int. If it were passed as a function argument, it would be automatically converted to a pointer to the first element, thus of type int *. Types int * and int ** are not compatible.
On the other hand, what you actually try to pass, &fr is the address of an array 4 int, of type int(*)[4]. This also is incompatible with int **, because arrays are not pointers.
You could write your function like this:
void swap_array_by_ptr(int (*a)[4], int (*b)[4]) {
int temp[4];
memcpy(temp, a, sizeof(a));
memcpy(a, b, sizeof(b));
memcpy(b, temp, sizeof(temp));
}
That would be compatible with the call in your code. Do note, however, that that is specific to array size 4, and you're not really gaining anything useful from that. You could, however, convert it to a template:
template<class T, std::size_t n>
void swap_array(T (*a)[n], T (*b)[n]) {
T temp[n];
memcpy(temp, a, sizeof(a));
memcpy(a, b, sizeof(b));
memcpy(b, temp, sizeof(temp));
}
That handles arrays of any element type and size,** as long as the sizes match. Of course, it scales as O(N) with array size, in both time and auxiliary space.
Such time scaling is unavoidable. To swap two objects you need to read each at least once and write each at least once, and that requires time proportional to the size of the objects. But you could reduce the space overhead to O(1) by swapping the arrays element by element in a loop. That would very likely be slower, but the time complexity would still be O(N).
Of course, you can also use std::swap() on arrays. It is quite similar to the template above, but uses references to the arrays instead of pointers to them.
*This is a specific case of a much more general behavior.
**So long as the temporary array does not turn out to be too large for the stack.
Change the swap_array_by_ptr function from 'swap_array_by_ptr(int** a, int** b)'
to 'swap_array_by_ptr(int* a, int* b)'.
void swap_array_by_ptr(int* a, int* b) {
int* temp = *a;
*a = *b;
*b = temp;
}
here's a link to a similar question: Swapping 2 arrays in C
I wrote the following function to store the (x, y, z) of a vtkPoint in an array of type double and size of 3*N, where N is the number of vertices (or points).
double* myClass::getMyPoints(void)
{
double* vertices = new double[this->m_numberOfVertices * 3];
for (vtkIdType ivert = 0; ivert < this->m_numberOfVertices; ivert++)
for (auto i = 0; i < 3; ++i)
this->m_points->GetPoint(ivert, &vertices[3 * ivert]);
return vertices;
}
where m_points is a member of myClass and is of type vtkSmartPointer<vtkPoints>.
This function does what I want and works just fine. I was wondering if there is an elegant way of getting the sequential pointers. I tried GetVoidPointer(), which looks like an elegant one-line code, to avoid the for loop but it does not get the coordinates correctly after the function returns vertices.
(double*)(m_points->GetData()->GetVoidPointer(0));
Could someone help me with this?
vtkPoints internally stores it's data as a float array instead of a double array. So you may need to modify your function to work with float* instead of double*. If we want to use double array for vtkPoints then we should call SetDataTypeToDouble() on the vtkPoints object.
#include <stdio.h>
#include <stdlib.h>
#include <vtkPoints.h>
#include <vtkSmartPointer.h>
int main(){
// Create data
auto N = 5;
vtkNew<vtkPoints> pts;
pts->SetDataTypeToDouble();
for(auto i=0; i < N; ++i)
pts->InsertNextPoint(rand()%100,rand()%100,rand()%100);
// Read using for loop
std::cout<< "Using for loop ... " << std::endl;
for( auto j=0; j < N; ++j ){
double p[3];
pts->GetPoint( j, p );
std::cout<< p[0] << "," << p[1] << "," << p[2] << std::endl;
}
// Read using GetVoidPointer()
std::cout<< "Using GetVoidPointer() ... " << std::endl;
auto data_ptr = (double*) pts->GetData()->GetVoidPointer(0);
for( auto k = 0; k < N; ++k )
std::cout<< *(data_ptr + 3*k) << ","
<< *(data_ptr + 3*k + 1) << ","
<< *(data_ptr + 3*k + 2) << std::endl;
return 0;
}
This gives result as follows:
Test that there are N = 5 tuples.
Using for loop ...
83,86,77
15,93,35
86,92,49
21,62,27
90,59,63
Using GetVoidPointer() ...
83,86,77
15,93,35
86,92,49
21,62,27
90,59,63
I'm trying to figure out print a full array in C++.
For example, I want the output to be x = [1,2,3,4,5....n]
How would I go about doing this? I already know how to print each element of the array using a simple for loop. For example in python, you could simply say x = [], make a for loop to append elements to the array, and print x.
So let's say I have this code.
int n = 10;
int m = 10;
double x[n];
// Generate vector of random values for x
for (int i = 0; i<n; ++i)
{
x[i] = (double)rand()/(double)RAND_MAX;
// Print each array element
// std::cout << x[i] << std::endl;
}
std::cout << x[n-1] << std::endl;
This obviously only spits out x[10] in this case. Where as I want x = [1...n] etc.
What is the simplest way of achieving this?
I'm using Eclipse on OSX. I use the g++ compiler that the Xcode developer tools has for the command line
You're looking for a range based for loop:
double x[] = { .0, .1, .2, .3, .4 };
// Iterate through all elements
for (auto d : x)
{
std::cout << d << std::endl;
}
Note that the above takes a copy of each element, so if you wanted to modify an element you'd need to use
for (auto& d : x)
instead.
Alternatively you could just use a normal for loop like you did originally:
for (int i = 0; i<n; ++i)
{
std::cout << x[i] << std::endl;
}
The range based for loop is the easiest though.
if you know something about STL , you can try to use iterator
code:
#include <iostream>
#include <iterator>
using namespace std;
int main()
{
int arr[5] = {1,2,3,4,5};
copy(arr, arr + sizeof(arr)/sizeof(int),ostream_iterator<int>(cout, " "));
cout << endl;
return 0;
}
#include <iostream>
using namespace std;
int getDegree()
{
int degree;
cout << "Enter degree of polynomial" << endl;
cin >> degree;
return degree;
}
int* getPoly(int degree)
{
cout << "Enter coefficients in order of power of x. e.g. for 2 + x + 3x^2, enter 2 then 1 then 3" << endl;
int coeff [degree +1];
for (int i = 0; i <= degree; i++)
{
cin >> coeff[i];
}
return coeff;
}
int* polyder(int p[], int degree)
{
int dp[degree];
for(int i = 0; i < degree; i++)
{
dp[i] = p[i+1] * (i+1);
}
return dp;
}
int main(int argc, const char * argv[])
{
int degree = getDegree();
int p = *getPoly(degree);
int dp = *polyder(&p, degree);
for(int i = 0; i < degree +1; i++)
cout << " " << p[i] << " x^" << i;
cout << endl;
for(int i = 0; i < degree +1; i++)
cout << " " << dp[i] << " x^" << i;
cout << endl;
return 0;
}
I am getting an error during the print statements.
I am not worried about the math involved, just how to pass the arrays between functions/methods.
Can anyone find why this is not working?
I am new to C++, used to Java.
Can anyone find why this is not working?
In C++ variables are destroyed when the scope in which they were declared ends. You return an address of a variable that doesn't exist when the function ends:
int* getPoly(int degree)
{
int coeff [degree +1];
// ...
return coeff;
}
If you wish the variable still exists after the function ends, you have to allocate it using new:
int* getPoly(int degree)
{
int *coeff = new int[degree +1];
// ...
return coeff;
}
And, at the end of your main function (or wherever you don't need the array anymore), call delete[] to deallocate the memory:
int *p = getPoly(degree);
delete[] p;
The Array name is essentially a pointer to the first element of the array (as you can see in the code above, I've declared p as a pointer to int), so you pass them to other functions just by providing their name:
int* polyder(int p[], int degree){/*do something here*/}
// <-- some other code
int *p = getPoly(degree);
int* returnedArray = polyder(p,degree);
First of all, the line
int coeff [degree +1];
is not a valid C++ statement unless 'degree' is a constant, even through some compilers may allow it.
Even if some compiler allowed it, the space for coeff is allocated from the stack and will be invalid after the function returns. Hence, the line
return coeff;
returns an memory location that will be invalid at its usage.
In order to return valid memory function, replace the line
int coeff [degree +1];
by
int* coeff = new int[degree];
You don't need degree+1 items in the array.
Similar changes are needed in the function polyder.
The thing to remember about arrays in C++ is that unlike Java, they are not objects (at least in the way they are in Java). They're simply pointers to a block of allocated memory, and the [] operator simply automatically does the math to move the pointer to the correct location.
When passing arrays between functions, you're basically just passing a pointer. Unless you want to get into some highly complicated and likely too much for your use case code, you should always pass the size of the array along with it to ensure that your indexes always stay in bounds.
And as the other answer points out, you need to ensure that the life cycle of the array lasts as long as you need it to. Simply returning a pointer to an object doesn't keep it alive like returning a reference does in Java.
#include <iostream>
using namespace std;
int main(){
int findMax(int *);
const int MAX = 100;
int values[MAX];
char ivals[256];
// Get the space-separated values from user input.
cin.getline(ivals, 256, '0');
char *helper;
// Clean input array and transfer it to values.
for(int i = 0; i < (MAX) && ivals[i] != 0; i++){
helper = ivals[i * 2];
values[i] = atoi(helper);
}
int mval = findMax(values);
cout << values << endl << mval;
return 0;
}
//Function to find the maximum value in the array
int findMax(int arr[]){
int localmax = 0;
for(int i = 0; i < (sizeof(arr)/sizeof(int)); i++){
if(arr[i] > localmax){
localmax = arr[i];
}
}
return localmax;
}
The purpose of this program is for the user to input a space-separated series of values ended by a 0. That array is then to be analyzed to find the max. I figured out how to convert what is originally a char[] into an int[] so that I can use the findMax() function on it without error but the sorting loop seems to have a problem of its own and when "cout << values << endl << mval;" is called, it returns only a memory address instead of what should be a non-spaced sequence of ints. Can anybody explain what I am doing wrong? It seems that I may have made some mistake using the pointers but I cannot figure out what.
Printing values won't print the contents of the array as you expect, it will print the memory location of the first element of the array.
Try something like this instead:
#include <iterator>
#include <algorithm>
// ...
copy(&values[0], &values[MAX], ostream_iterator(cout, " "));
Sorry I can't post actual working code, but your original post is a mess with many syntax and syntactic errors.
EDIT: In the interest of being more complete and more approachable & understandable to beginners, I've written a small program that illustrates 4 ways to accomplish this.
Method 1 uses copy with an ostream_iterator as I've done above.
Method 2 below is probably the most basic & easiest to understand.
Method 3 is a C++0x method. I know the question is tagged C++, but I thought it might be educational to add this.
Method 4 is a C++ approach using a vector and for_each. I've implemented a functor that does the dumping.
Share & Enjoy
#include <iostream>
#include <iterator>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std;
struct dump_val : public unary_function<int,void>
{
void operator()(int val)
{
cout << val << " ";
}
};
int main(){
int vals[5] = {1,2,3,4,5};
// version 1, using std::copy and ostream_iterator
copy(&vals[0], &vals[5], ostream_iterator<int>(cout, " "));
cout << endl;
// version 2, using a simple hand-written loop
for( size_t i = 0; i < 5; ++i )
cout << vals[i] << " ";
cout << endl;
// version 3, using C++0x lambdas
for_each(&vals[0], &vals[5], [](int val)
{
cout << val << " ";
}
);
cout << endl;
// version 4, with elements in a vector and calling a functor from for_each
vector<int> vals_vec;
vals_vec.push_back(1);
vals_vec.push_back(2);
vals_vec.push_back(3);
vals_vec.push_back(4);
vals_vec.push_back(5);
for_each( vals_vec.begin(), vals_vec.end(), dump_val() );
cout << endl;
}
When you pass around an array of X it's really a pointer to an array of X that you're passing around. So when you pass values to cout it only has the pointer to print out.
You really should look into using some of the standard algorithms to make your life simpler.
For example to print all the elements in an array you can just write
std::copy(values, values+MAX, std::ostream_iterator<int>(std::cout, "\n"));
To find the max element you could just write
int mval = *std::max_element(values, values+MAX);
So your code becomes
#include <iostream>
using namespace std;
int main(){
const int MAX = 100;
int values[MAX];
char ivals[256];
// Get the space-separated values from user input.
cin.getline(ivals, 256, '0');
char *helper;
// Clean input array and transfer it to values.
for(int i = 0; i < (MAX) && ivals[i] != 0; i++){
helper = ivals[i * 2];
values[i] = atoi(helper);
}
copy(values, values+MAX, ostream_iterator<int>(cout, "\n"));
cout << *std::max_element(values, values+MAX);
return 0;
}
Doing this removes the need for your findMax method altogether.
I'd also re-write your code so that you use a vector instead of an array. This makes your code even shorter. And you can use stringstream to convert strings to numbers.
Something like this should work and is a lot less code than the original.
int main(){
vector<int> values;
char ivals[256];
// Get the space-separated values from user input.
cin.getline(ivals, 256, '0');
int temp = 0;
stringstream ss(ivals);
//read the next int out of the stream and put it in temp
while(ss >> temp) {
//add temp to the vector of ints
values.push_back(temp);
}
copy(values.begin(), values.end(), ostream_iterator<int>(cout, "\n"));
cout << *std::max_element(values.begin(), values.end());
return 0;
}
Array of int is promoted to a pointer to int when passed to a function. There is no operator << taking ordinary array. If you want to use operator << this way, you need to use std::vector instead.
Note: it is possible technically to distinguish array when passed to a function using template, but this is not implemented for standard operator <<.
for(int i = 0; i < (sizeof(arr)/sizeof(int)); i++){
sizeof(arr) here is the size of the pointer to the array. C++ will not pass the actual array, that would be grossly inefficient. You'd typically only get one pass through the loop. Declare your function like this:
int findMax(int* arr, size_t elements) {
//...
}
But, really, use a vector.
Oh, hang on, the question. Loop through the array and print each individual element.