How to print double pointer array - c++

I have two double pointer array, which I want to print
but somehow I am not able to do it..
double *noise_feature = new double[5];
double *basic_feature = new double[39];
noise_feature_extraction(sig, len, noise_feature);
basic_feature_extraction(sig, len, basic_feature);
cout << "\n";
printf("Noice features are");
for (auto i = noise_feature.begin(); i != noise_feature.end(); ++i)
cout << *i << " ";
cout << "\n";
printf("Basic features are");
for (auto i = basic_feature.begin(); i != basic_feature.end(); ++i)
cout << *i << " ";
cout << "\n";
This gives error like this
Pan_Tompkins.cpp:992:29: error: member reference base type 'double *' is not a structure or union
for (auto i = noise_feature.begin(); i != noise_feature.end(); ++i)
~~~~~~~~~~~~~^~~~~~
Pan_Tompkins.cpp:992:57: error: member reference base type 'double *' is not a structure or union
for (auto i = noise_feature.begin(); i != noise_feature.end(); ++i)
I tried printing this way
printf("%g",noise_feature);
printf("%g",basic_feature);
This does not give error but also does not print anything.
How can I print this two double array to see their value?

You request a raw array on the heap and discard the info how many elements it has. Recall that
double *noise_feature = new double[5];
declares nothing but a pointer to double. The fact that you know it's a contiguous array of length 5 can be used in different way. Either you keep that magic number literal in your code;
for (auto value = noise_feature; value != noise_feature + 5; ++value)
// not maintainable, but works: ^^^^^^^^^^^^^^^^^
cout << *value << " ";
Or you go with a raw array on the stack. Here, the length is baked into the type and hence not lost. You could use a range-based for loop to iterate over it, for example.
double noise_features[5];
// ...
for (double value : noise_features)
std::cout << value << ' ';
However, the preferred solution is using either std::vector if the size of your sequence is only known at runtime, or std::array if it's a fixed-length sequence.

You declared two pointers
double *noise_feature = new double[5];
double *basic_feature = new double[39];
Pointers are scalar objects that do not have the member functions begin and end.
So you have to use the magic numbers 5 and 39 to output the allocated arrays pointed to by the pointers.
For example
cout << "\n";
printf("Noice features are");
for ( size_t i = 0; i < 5; ++i )
cout << noise_feature[i] << " ";
cout << "\n";
printf("Basic features are");
for ( size_t i = 0; i < 39; ++i )
cout << basic_feature[i] << " ";
cout << "\n";
The same can be done using pointers as for example
cout << "\n";
printf("Noice features are");
for ( auto p = noise_feature; p != noise_feature + 5; ++p )
cout << *p << " ";
cout << "\n";
printf("Basic features are");
for ( auto p = basic_feature; p != basic_feature + 39; ++p )
cout << *p << " ";
cout << "\n";
Pay attention to that instead of "manually" allocating dynamically arrays you could use the standard container std::vector as for example
#include <vector>
//...
std::vector<double> noise_feature( 5 );
//...
cout << "\n";
printf("Noice features are");
for ( const auto &item : noise_feature )
cout << item << " ";
cout << "\n";
//...

Arrays defined with statements like array_name[element_count] are not objects of any class!
Arrays are actually pointers to continuous memory. So, they don't have any methods and member functions. So your code will fail to compile. So instead of this:
for (auto i = noise_feature.begin(); i != noise_feature.end(); ++i)
Use this:
for (auto i = noise_feature; i != noise_feature + 5; ++i)
Or this:
for (auto i = std::begin(noise_feature); i != std::end(noise_feature); ++i)
Or you can store it in a std::vector<double> object. Also, why you used printf when C++ provides std::cout ?

Related

Output value of array rather than memory address of array

So I've made a basic polynomial class in C++ which stores the coefficients of these polynomials dynamically on the heap. I'm currently in the process of overloading operators so that I can add/subtract polynomials together in order to simplify them etc.
However I'm getting unexpected results when I try to overload the * operator. It looks like instead of returning the value of an index in the array it is returning the position of the array.
This is my *operator method in my .cpp file:
Polynomial Polynomial::operator*(Polynomial p) {
int maxDegree = (degree)+(p.degree - 1);
int *intArray3 = new int[maxDegree];
int i, j;
for (int i = 0; i < degree; i++) {
for (int j = 0; j < p.degree; j++) {
cout << getCoef(i) << " * " << p.getCoef(j) << " = " << getCoef(i)*p.getCoef(j) << endl;
intArray3[j] += (getCoef(i))*(p.getCoef(j));
cout << " intArray3[" << j << "] contains : " << intArray3[j] << endl;
}
}
return Polynomial(maxDegree, intArray3);}
The lines:
cout << getCoef(i) << " * " << p.getCoef(j) << " = " << getCoef(i)*p.getCoef(j) << endl;
and
cout << " intArray3[" << j << "] contains : " << intArray3[j] << endl;
return
10 * 1 = 10
intArray3[0] contains : -842150441
in my console. I'm assuming that the problem lies with my use of pointers somewhere but I can't for the life of me think why. I implemented this overload in a similar way to my + and - overloads and they work fine. Any assistance would be greatly appreciated. Cheers.

How can I assign a different address to an array?

I want to pass an array to a function, then point that array variable to a new address altogether within said function.
I realize that arrays behave as pointers to the adress of their first element when passed to a function, so why the heck won't the address change for my array variable in main?
#include <iostream>
using namespace std;
void passArrayByReference(int * array) { //passing array as. pointer should let us modify it's address, correct?
cout << "Address of array in function is: " << array << endl;
int * localArray = new int [2];
//put some dummy values in our localArray
localArray[0] = 9;
localArray[1] = 9;
array = localArray;
cout << "Address of array in function is now: " << array << endl;
}
int main()
{
int * array = new int [2];
int totalElements = 2;
//put some initial values into our dynamic 1D array
array[0] = 0;
array[1] = 1;
//print our initial values
for(int i = 0; i < totalElements; i++)
cout << array[i] << endl;
cout << "Address of array in main: " << array << endl;
passArrayByReference(array);
cout << "Address of array in main: " << array << endl;
return 0;
}
You are on the right track, but you just need to include the '&' symbol in your function header. The '&' symbol is used to pass an argument by reference, as opposed to by value.
In this case you are passing the address to the first element of your array by reference, meaning that you can modify that address in the function, and the changes will be reflected in your main function.
#include <iostream>
using namespace std;
void passArrayByReference(int * &array) {
cout << "Address of array in function is: " << array << endl;
int * localArray = new int [2];
//put some dummy values in our localArray
localArray[0] = 9;
localArray[1] = 9;
array = localArray;
cout << "Address of array in function is now: " << array << endl;
}
int main()
{
int * array = new int [2];
int totalElements = 2;
//put some initial values into our dynamic 1D array
array[0] = 0;
array[1] = 1;
//print our initial values
for(int i = 0; i < totalElements; i++)
cout << array[i] << endl;
cout << "Address of array in main is: " << array << endl;
passArrayByReference(array);
cout << "Address of array in main is now: " << array << endl;
//now print the values of our 'new' array
cout << "The values of array are now:" << endl;
for(int i = 0; i < totalElements; i++)
cout << array[i] << endl;
return 0;
}
First, you have to pass pointer by pointer or reference to make persistent change to it - that is change original pointer and not only copy of it in function body:
void passArrayByReference(int *&array) {
//...
array = new_address;
std::cout << "Address of array in function is now: " << array << std::endl;
}
// and here it is the same
And second you should assign valid address new_address and take care of memory that array referenced just before it entered the function, to avoid memory leak.
Pointers are variables as well.
That's why you need to pass array as a reference to passArrayByReference so you don't just modify the copy of it.
void passArrayByReference(int *&array)

Array data is 'lost' after passing the array to another object

I'm having a problem where the objects in my array are lost when I pass the array through a constructor. My first guess was that I needed to change it to an array of pointers but that resulted in a segfault. My next guess was that I needed to copy the array data after passing it but that also didn't work. Here's the problem code:
Universe Object:
class Universe {
public:
Star stars[]; int starsLength;
Planet planets[]; int planetsLength;
public:
Universe(Star st[], int stl, Planet pl[], int pll) {
stars < st; starsLength = stl;
planets < pl; planetsLength = pll;
}
Universe() {
}
public:
void render() {
for(int i = 0;i < starsLength;i++) {
//std::cout << "STAR: " << stars[i].location.x << "," << stars[i].location.y << " " << stars[i].size << " " << stars[i].color.r << "," << stars[i].color.g << "," << stars[i].color.b << "\n";
renderCircle(stars[i].location, stars[i].size, stars[i].color);
}
for(int i = 0;i < planetsLength;i++) {
renderCircle(planets[i].location, planets[i].size, planets[i].color);
}
}
void renderCircle(Point location, float size, Color color) {
glBegin(GL_LINES);
glColor3f(color.r,color.g,color.b);
glVertex2f(location.x+size, location.y+size);
glVertex2f(location.x-size, location.y-size);
glVertex2f(location.x-size, location.y+size);
glVertex2f(location.x+size, location.y-size);
glEnd();
}
};
Method that creates the Universe and gives it the array:
Universe buildUniverse(int size, int seed) {
Point bounds = Point{static_cast <float> (size),static_cast <float> (size)}; //0,0 to size,size
int starCount = min(size/10,random(size/5));
int planetCount = min(size/3,random(size));
Star stars[starCount];
Planet planets[planetCount];
//std::cout << "-- Created " << starCount << " stars and " << planetCount << " planets...\n";
for(int i = 0;i < starCount;i++) {
Point location = {random(bounds.x),random(bounds.y)};
Point velocity = {random(bounds.x/100.0f),random(bounds.y/100.0f)};
float size = random(bounds.x/100.0f);
float mass = random(size*(random(1.0f)+0.5f));
Color color = {1.0f,1.0f,1.0f};
stars[i].setStar(location,velocity,size,mass,color);
}
for(int i = 0;i < planetCount;i++) {
Point location = {random(bounds.x),random(bounds.y)};
Point velocity = {random(bounds.x/100.0f),random(bounds.y/100.0f)};
float size = random(bounds.x/100.0f);
float mass = random(size*(random(1.0f)+0.5f));
Color color = {random(1.0f),random(1.0f),random(1.0f)};
planets[i].setPlanet(location,velocity,size,mass,color);
}
Universe uni = {stars, starCount, planets, planetCount};
std::cout << "Star in array: " << stars[0].location.x << "," << stars[0].location.y << " " << stars[0].size << " " << stars[0].color.r << "," << stars[0].color.g << "," << stars[0].color.b << "\n";
std::cout << "Star passed to uni in an array: " << uni.stars[0].location.x << "," << uni.stars[0].location.y << " " << uni.stars[0].size << " " << uni.stars[0].color.r << "," << uni.stars[0].color.g << "," << uni.stars[0].color.b << "\n";
return uni;
}
Output of of the program:
Building universe...
Star in array: 39.922,39.155 0.167611 1,1,8.85715e-39
Star passed to uni in an array: 7.00649e-45,2.24208e-44 0.0282954 5.90446e-39,1.4013e-45,1.4013e-45
Initializing threaded renderer...
Starting simulation...
What am I doing wrong?
First, your code is not valid C++. Declaring empty arrays using [] does not exist in C++.
So the first thing is to turn this into valid C++ that still preserves what you're trying to accomplish. One solution is to use std::vector:
#include <vector>
class Universe {
public:
std::vector<Star> stars;
std::vector<Planet> planets;
public:
Universe(const std::vector<Star>& st,
const std::vector<Planet>& pl) : stars(st), planets(pl) {}
};
Note the replacement of the non-C++ code with std::vector. Also note that we initialize the vectors using the initializer-list.
Last, note that we no longer need to keep the sizes as separate member variables. Why? Because a vector knows its size by calling the vector::size() member function. For example:
for(int i = 0;i < starsLength;i++) {
can be replaced with
for(int i = 0;i < stars.size();i++) {
In your buildUniverse function, use the following changes:
Universe buildUniverse(int size, int seed) {
Point bounds = Point{static_cast <float> (size),static_cast <float> (size)}; //0,0 to size,size
int starCount = min(size/10,random(size/5));
int planetCount = min(size/3,random(size));
std::vector<Star> stars(starCount);
std::vector<Planet> planets(planetCount);
//...
Universe uni(stars, planets);
The rest of the code stays the same. Now, if after the call to create the Universe, you see that the vectors didn't pass the correct information, then look further. The code above conforms to "normal" C++, such that we can go further and figure out the issue.

Memory location for a pointer passed in a function gets deleted [duplicate]

This question already has answers here:
Pointer errors in the method of transmission(c++)
(4 answers)
Closed 8 years ago.
Question: I can't seem to set a pointer to an address that was created inside of a function. It always gets set to Null, how do I fix this?
Problem: I believe the problem is caused by the variable being created inside of another function. What's happening is that after the function executes, the pointer is set to NULL again.
Code:
void listAdd(int *list, int &length) {
int* tempList = new int[ length + 1 ];
for( int i = 0; i < length; i ++ )
{
(tempList)[ i ] = (list)[ i ];
}
cout << " Previous adress: " << hex << list << endl;
if ( list != NULL )
delete[] list;
list = new int[ length + 1 ];
cout << " New address: " << hex << list << endl << dec;
for( int i = 0; i < length; i ++ )
{
(list)[ i ] = (tempList)[ i ];
}
delete[] tempList;
cout << " Enter a number: ";
int stored = 0;
cin >> stored;
(list)[length -1] = stored;
length ++;
cout << " Length: " << length << "\n";
cout << " value at array point 0: " << (list)[length -1];
cout << "\n retry " << (list)[length-1] <<"\n";
cout << "\n \n \n This is pointing to 0x" << hex << list << '\n' << flush;
}
It seems you would like the changes to list to be valid after the function returned: since list is passed by value, the object manipulated inside the function happens to be a copy of the one you passed in. You probably either want to pass the object by reference, i.e.:
void listAdd(int*& list, int &length) {
// ...
}
... or return the result
int* listAdd(int* list, int& length) {
// ...
return list;
}
list = listAdd(list, length);
Well, realistically, you really really want to encapsulate the objects in a class or just use std::vector<int>.

New ISO scoping rule for " for LOOP"

I have a piece of code that was written by someone else before the New ISO come into effect.
The for LOOP in for (pa=a.begin(), i=0; pa != a.end(); ++pa) has a little trouble executing because of the i=0 part of the syntax. Also, I had to prefix the other for loop syntaxes to read for ( int i .....) with the int before the i. However, I don't know how to fix the int i=0 in this line: for (pa=a.begin ( ), i=0; pa != a.end ( ); ++pa). Please help me out.
for ( int i = 0; pa != a.end(); ++pa)
*pa = ++i;
for (int i=0; i<10; i++)
std::cout << "a[" << i << "]=" << a[i] << std::endl;
// int i; // note that this will work, but I do not want this extra line.
for (pa=a.begin(), i=0; pa != a.end(); ++pa)
std::cout << "a[" << i++ << "]=" << *pa << std::endl;
An extra declaration outside the for loop is the only sensible way to have two iteration variables of unrelated types in C++98 and later versions of the language. The initialiser can either be a single expression or a single declaration, and a declaration can't declare variables of multiple unrelated types.
If you really want a one-liner in this situation, then you could use this monstrosity:
for (int i = ((pa = a.begin()), 0); pa != a.end(); ++pa, ++i)
If you do that sort of thing regularly, then make sure that no-one who maintains your code knows where you live.
No, you can declare only variables of one type inside the for. If your problem is scope then you may enclose the loop inside a block (for some nice examples look boost source code for loop macros):
for ( int i = 0; pa != a.end(); ++pa)
*pa = ++i;
for (int i=0; i<10; i++)
std::cout << "a[" << i << "]=" << a[i] << std::endl;
{
int i = 0;
for (pa=a.begin(); pa != a.end(); ++pa)
std::cout << "a[" << i++ << "]=" << *pa << std::endl;
}
If you simply want to make it more nice then the answer is no, you can't.
EDIT
The best trick I saw to do what you need and to keep it clear is on this answer on SO. Instead of multiple variables you can use an unnamed struct declared inline:
for (struct { int i; iterator it; } d = { 0, pa.begin() }; d.it != a.end(); ++d.i, ++d.it )
std::cout << "a[" << d.i << "]=" << *d.it << std::endl;
It's a little bit more prolix (so I wonder if what you save with the extra line is re-payed) but you make clear your intent and you keep code readable (moreover you can use it to pack any number and any type of variables).