简体   繁体   中英

Memset on pointer of pointers - why won't it work?

I'm implementing a matrix library in c. I've already made a vector library and I have defined a matrix to be nothing but a collection of pointers pointing to vectors (so each pointer references a vector struct which is the matrices column.) I have a pointer of pointers instead of an array of pointers because a) I want jagged matrices to be possible b) I want vector operations to work on the individual columns of the matrix and c) I want the actual matrix to be dynamic.

Here is the matrix type definition:

    typedef struct mat {
    size_t alloc; // num of allocated bytes
    size_t w, h; // dimensions for the matrix
    vec** cols; // each column is a vector
    } mat;

Suppose I want to resize the dimensions of the matrix. The following code works just fine for me:

    void resizem(mat* m, size_t w, size_t h) {
    m -> alloc = w * VECTOR_SIZE;
    m -> cols = realloc(m -> cols, m -> alloc);
//    if(w > m -> w) {
//        memset(m -> cols + m -> w, init_vec(h), (w - (m -> w)) * VECTOR_SIZE);
//    }
    if(w > m -> w) {
        for(int i = m -> w; i < w; i++) {
            m -> cols[i] = init_vec(h);
        };
    }
    for(int i = 0; i < w; i++) {
        resizev(m -> cols[i], h);
    };
    m -> w = w;
    m -> h = h;
}

My approach was as follows: 1) re-compute the amount of bytes to reallocate and store this in the matrix struct (amount of columns * column size) 2) reallocate memory to the columns 3) if the matrix 'grew' in width then each new column needs to be initialised to a default vector. 4) resize the size of each vector in the matrix.

Note the commented out lines however. Why can't I just add an offset (the size of the former matrix) to the column pointers and use memset on the remaining columns to initialise them to a default vector? When I run this it doesn't work so I use a for loop instead.

Note that if it helps at all here is the github link to the vector library so far: Github link

When you use memset() you only call initvec() once. So all the elements would point to the same vector.

Also, memset() assigns the value to each byte in the array. But your row is supposed to contain pointers, not bytes.

BTW, your code is leaking lots of memory, because you never free() the old pointers in the row. You need to do this before calling realloc() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM