Page 160 - ARM 64 Bit Assembly Language
P. 160

146 Chapter 5


                                 Listing 5.38 Initializing an array of structured data in C.

                1  #include <stdio.h>
                2  #include <stdlib.h>
                3
                4  /* image size */
                5  const int width = 100;
                6  const int height = 100;
                7
                8  /* define structure for a pixel */
                9  struct pixel {
                10  unsigned char red;
                11  unsigned char green;
                12  unsigned char blue;
                13  };
                14
                15  int main(void)
                16  {
                17  // allocate image
                18  struct pixel *image = malloc(width * height * sizeof(struct pixel));
                19  if (image == NULL) {
                20    fprintf(stderr, "Error: Out of memory.\n");
                21    return 1;
                22  }
                23
                24  // initialize all pixels in the image to black
                25  for (int j = 0; j < height; j++) {
                26    for (int i = 0; i < width; i++) {
                27      image[j*width+i].red = 0;
                28      image[j*width+i].blue = 0;
                29      image[j*width+i].green = 0;
                30    }
                31  }
                32
                33  // delete the image
                34  free(image);
                35
                36  return 0;
                37  }




                  to zero on each iteration of the loop, why not use a single store instruction to set sixteen bytes
                  to zero on each iteration? The only problem with this approach is that we must consider the
                  possibility that the array may end in the middle of the quad-word. However this can be dealt
                  with by using two consecutive loops. The first loop sets one quad-word of thearraytozeroon
                  each iteration, and the second loop finishes off any remaining bytes. Listing 5.41 shows the
   155   156   157   158   159   160   161   162   163   164   165