Qwerty
Qwerty

Reputation: 153

dynamic malloc for two-dimensional array

I alloced block of memory for matrix. Than in cycle I remember poiters to the lines.
I got Unhandled exception: Access violation writing location 0x00557148 in _tmain cycle for. What did I wrong?

double **d; 

#define COUNT 10 

int create()
{
    d = (double**) malloc(COUNT * sizeof(double*));
    if (!d)
        return 0; 
    int size = COUNT * sizeof(double); 
    double *_new =  (double*) malloc(COUNT * size);

    if (!_new)
        return 0; 
    for (int i = 0; i < COUNT; i++) {
        d[i] = _new;
        _new += size; 
    }

    return 1; 
}

int _tmain(int argc, _TCHAR* argv[])
{
    double *_d; 
    if (create()) {
        for(int i = 0; i < COUNT; i++) {
            _d = d[i]; 
            for (int j = 0; j < COUNT; j++)
                _d[j] = 5; 
        }
    } else
        return -1;

    return 0;
}

Upvotes: 1

Views: 760

Answers (1)

Alex
Alex

Reputation: 759

I'm pretty sure you need to change _new += size to _new += COUNT

Upvotes: 1

Related Questions