• C

Pointers and Arrays

I am having a little trouble with the following code, it works for c++ but i  get violation errors when compiled in C ...i am using visc++7.1


code:

struct test
{
unsigned char *data;
}

test *i;
unsigned char temp;
int h;

    for( h = 0; h < i->m_size * 3; h += 3 )
    {
            temp = i->data[h]; // allways gives access violation error's here
    }

nutterxAsked:
Who is Participating?
 
sunnycoderCommented:
>unsigned char *rgb = (unsigned char*)i->m_data[0];
i has no member m_data .. I am guessing that you want it to point to i->data
The assignment should have been rgb = i->data
i->data[0] would be a unsigned char and not pointer to it

>for( h = 0; h < i->m_size * 3; h += 3 )

you have m_size of data and you are accessing upto m_size*3. You clearly are trying to read beyond the memory you allocated.
0
 
sunnycoderCommented:
Hi nutterx,

test * i is uninitialized. It is a dangling pointer and could be pointing to anything.
Also there is no member m_size in struct test!!! Is this the exact code ?

Cheers!
Sunnycoder
0
 
nutterxAuthor Commented:
sorry i cut alittle too much out ;-)

struct test
{
int m_size;
unsigned char *data;
}

i am actually trying to convert a BMP from BGR to RGB

      i->data = (unsigned char *)malloc(Infoheader.biSizeImage);
        i->m_size = Infoheader.biSizeImage
      fread(i->data,1,Infoheader.biSizeImage,fptr);

i can actually display the image ok using BGR but i want it to be RGB so i am trying to convert it
here is all the code for the convert
 
        unsigned char temp;
      unsigned char *rgb = (unsigned char*)i->m_data[0];
    for( h = 0; h < i->m_size * 3; h += 3 )
    {
            temp = rgb[h]; //access violation here!!
            rgb[h] = rgb[h + 2];
                rgb[i + 2] = temp;
    }



0
Making Bulk Changes to Active Directory

Watch this video to see how easy it is to make mass changes to Active Directory from an external text file without using complicated scripts.

 
nutterxAuthor Commented:
oops i do initialise "test i;" too:

i = (test *)malloc(sizeof(test));

like i said the code works all ok just not when i try to convert from gbr to rgb,so im very sure everything is initialised ok.
0
 
rajeev_devinCommented:
>> oops i do initialise "test i;" too:
Ok you intialize test i;
But did you allocated space for unsigned char *data;
0
 
rajeev_devinCommented:
Is your data allocated ? Something like this

test *i;
i = (test *)malloc(sizeof(test));
i->data = malloc(...);
0
 
nutterxAuthor Commented:
thanks sunny, i can't believe i missed that!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.