dynamic array not allocating correctly

I need to allocate an array of unsigned chars to hold rgb data. Here's the code:

1
2
3
4
int size = vp.vres * vp.hres * 3;
std::cout << size << std::endl;
pixel_data = new uchar[size];
std::cout << sizeof(pixel_data)/sizeof(uchar) << std::endl;


This writes out:

7500
4


What am I doing wrong here? Why is the allocated space for the array so much smaller than it should be?

EDIT: uchar is just typedef unsigned char uchar;
Last edited on
fafner wrote:
What am I doing wrong here?

Nothing. pixel_data is a pointer, not an array. sizeof(pixel_data) returns the size of a pointer, which is 4 bytes.
Ah, ok, I see. It's just that my program crashes because somehow there's not enough space allocated, so I thought maybe this was the cause. Oh well. Thanks anyway;)

EDIT: So how would I go about to find the actual size of the array?
Last edited on
Maybe sizeof(uchar[size]) for this case
The size of the array would be...size >_>
Oh yeah... Kind of obvious in hindsight.
If you want to check whether the crash is caused by writing
past the bounds of your array, you could do something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <vector>
using namespace std;

template <class T>
struct DynamicArray
{
    vector<T> data;

    DynamicArray(int n):data(n) {}

    T & operator[](int i) { return data.at(i); }
};

int main()
{
    DynamicArray<int> arr(5);

    cout << arr[4] << endl;
    cout << arr[5] << endl;

    return 0;
}

http://cplusplus.com/reference/stl/vector/at/
Last edited on
Topic archived. No new replies allowed.