Dave Brown Dave Brown - 1 year ago 80
C Question

Array Syntax Confusion in C

I'm trying to teach myself C via the iTunes University/Harvard CS50 course. In it a program is to be written which resizes a bitmap image file. To do this, I've defined an array (buffer) and written the necessary code for the program to work - it does work. However, I had to cheat and Google an answer as I couldn't figure it out, and I don't understand a particular piece of syntax in the solution and am hoping someone can help.

The block of code looks like the below and I've put in the comments my specific point of confusion:

// allocate array to hold scanline pixels - this is the array I define
RGBTRIPLE *buffer = malloc(bi.biWidth * sizeof(RGBTRIPLE));

// declare variable to track position in buffer array
int count;

// iterate over infile's scanlines
for (int i = 0, height = abs(oldHeight); i < height; i++)
// initialize count var to 0
count = 0;

// iterate over pixels in scanline
for (int j = 0; j < oldWidth; j++)
// temporary storage

// read RGB triple from infile
fread(&triple, sizeof(RGBTRIPLE), 1, inptr);

// place pixel in buffer array n times
for (int k = 0; k < n; k++)
// below is the confusion. Some sudo code would be great!
*(buffer+(count)) = triple;

Answer Source

First the variable buffer is not an array variable. It is a pointer variable. Remember that arrays are not pointers.
Now the line

 *(buffer+(count)) = triple;  

is using pointer arithmetic. buffer is a pointer to the RGBTRIPLE type and after allocating space to it, it is pointing to the first block of that memory. Adding the value of count to it increments it to the next block, i.e, giving the address of the next block. Dereferencing this address with * operator gives the value stored at that address. It can also be written as

buffer[count] = triple;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download