recoN_90
recoN_90

Reputation: 33

Pointer to 2D array as function parameter

This C++ code worked for me so far:

Main.cpp:

unsigned __int16** image_data; 
image_data = Grabber->get_image_data(1);

interface.cpp:

unsigned __int16** Grabber::get_image_data(int image_num) {
    unsigned __int16 **pixel_values = 0;
    pixel_values = new unsigned __int16*[height];
    for (int h = 0; h < height; h++) {
        pixel_values[h] = new unsigned __int16[width];
        for  (int w = 0; w < width; w++) {
            pixel_values[h][w] = ...;
        }
    }
    return pixel_values;
}

But now I would like to pass the array as pointer to the function. I tried it like in following code, but it doesnt work anymore.

Main.cpp:

unsigned __int16** image_data;
Grabber->get_image_data(1, &image_data);

Interface.cpp:

int Grabber::get_image_data(int image_num, unsigned __int16*** image_data) {
    *image_data = new unsigned __int16*[height];
    for (int h = 0; h < height; h++) {
        *image_data[h] = new unsigned __int16[width];
        for  (int w = 0; w < width; w++) {
            *image_data[h][w] = ...;
        }
    }
    return 0;
}

Are there any errors in reasoning by me?

Upvotes: 3

Views: 112

Answers (1)

molbdnilo
molbdnilo

Reputation: 66371

*image_data[h] means *(image_data[h]) (that is, image_data[h][0]), not (*image_data)[h] (or image_data[0][h]).
The latter is what you want.

It's easier to get it right if you introduce a local variable:

int ..::get_image_data(int image_num, unsigned __int16*** image_data) {
    ...
    unsigned __int16** data = new unsigned __int16*[height];
    *image_data = data;
    for (int h = 0; h < height; h++) {
        data[h] = new unsigned __int16[width];
        for  (int w = 0; w < width; w++) {
            data[h][w] = ...;
        }
    }
    return 0;
}

Upvotes: 6

Related Questions