lofdi
lofdi

Reputation: 1

C++ pointer to array and for loop;

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!

Upvotes: 0

Views: 453

Answers (2)

Luchian Grigore
Luchian Grigore

Reputation: 258548

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.

Upvotes: 0

Borealid
Borealid

Reputation: 98459

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?

Upvotes: 2

Related Questions