0

i'm pretty new to C++, and have a little problem with that piece of code. I want to put 1 in every cell of array which should be created with dynamic memory allocation. I believe i made something similar a few months ago in c with malloc. When I print out results (g++ Linux) it shows that only first column (when we treat every tenth cell of array as beginning of new column) is filled with ones. Others are printed as a adresses to memory.

#include "stdafx.h"
#include <iostream>

class TestOfForVector {
public:
double* tabX;
double* tabY;
int n;
TestOfForVector(int getN){
    n = getN;
    tabY = new double[n*n];
    //tabX = new double[n];
    for(int i = 0; i < n; i ++ ){
        for(int j = 0; j <n; j++){
        tabY[j+i*n] = 1.0;
        std::cout<<tabY[j+i*n]<<std::endl;
        }
    }
}


~TestOfForVector(){
    delete [] tabX;
    delete [] tabY;
}
};


int main(int argc, _TCHAR* argv[])
{   
TestOfForVector newboy(10); //it will be defined by user input;
return 0;
}

Sorry for probably trivial question, but i couldn't find answer on the internet. Best regards, Lukasz!

2
  • 2
    Use #include <vector> and use std::vector<double> instead of an array. Commented Apr 26, 2012 at 17:10
  • 1
    I cannot reproduce your results: ideone.com/VgIqt -- Are you sure this is the same code you're running? Commented Apr 26, 2012 at 17:10

2 Answers 2

2

Your code is correct, and (after commenting out your delete[] tabX since you commented out the creation code) it runs and produces a column of ones on my machine.

I do not know what the stdafx.h header is supposed to be - the normal signature for main is (int argc, char** argv). So I removed that header prior to compiling with g++. You said you were on Linux, so using Visual Studio things seems odd, no?

Sign up to request clarification or add additional context in comments.

Comments

0

You're running into undefined behavior in the destructor:

delete [] tabX;

because the pointer tabX is dangling as it's not initialized.

Besides that, your code is fine, although stdafx.h is the precompiled header file used under Win and _TCHAR is a MSVS define for a wide char and you said you're compiling under Linux.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.