Thread: Adding Two 2D Arrays Together

  1. #1
    Registered User
    Join Date
    Dec 2021
    Posts
    34

    Adding Two 2D Arrays Together

    I've been trying to add two 2D arrays together with different element types: red, green and blue that point to a structure. I'm pretty sure the two arrays are read in correctly I just don't think they're added together right...
    Code:
    RGBArray = (PPMPixel **)malloc(head[1].height*sizeof(PPMPixel*)); //Points to malloc
        if((RGBArray == NULL))
        {
            printf("\tError allocating memory to the array\n");
        }
        else
        {
            printf("\tMemory allocated to the PPM array sucessfully\n"); 
        }
        for (i=0;i<head[1].height;i++)
        {
            RGBArray[i] = (PPMPixel *)malloc(head[1].width*sizeof(PPMPixel));
        }
        for (j=0;j<head[1].height;j++)
        {
            for (i=0;i<head[1].width;i++)
            {
                RGBArray[j][i].red = (AddArray1[j][i].red + AddArray2[j][i].red);
                RGBArray[j][i].green = (AddArray1[j][i].green + AddArray2[j][i].green); 
                RGBArray[j][i].blue = (AddArray1[j][i].blue + AddArray2[j][i].blue);
                //printf("%d ", RGBArray[j][i].red);
                //printf("%d ", RGBArray[j][i].green);
                //printf("%d ", RGBArray[j][i].blue);
            }     
        }

  2. #2
    Registered User
    Join Date
    Dec 2017
    Posts
    1,468
    Well, obviously you can't just add the values together since you could end up with a result that is higher than the maximum allowed value.
    The whole problem with the world is that fools and fanatics are always so certain of themselves, but wiser people so full of doubts. - Bertrand Russell

  3. #3
    Registered User
    Join Date
    Dec 2021
    Posts
    34
    Solved it! It was just a pointer mistake. This code I sent was fine.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Adding Arrays
    By jocdrew21 in forum C Programming
    Replies: 14
    Last Post: 08-12-2013, 10:06 AM
  2. Adding numbers with arrays
    By Oliveira in forum C Programming
    Replies: 4
    Last Post: 04-16-2009, 10:25 PM
  3. Now I need help adding arrays
    By nifear4 in forum C Programming
    Replies: 28
    Last Post: 10-30-2008, 10:18 AM
  4. Adding arrays with pointers - help
    By chip.litch in forum C Programming
    Replies: 2
    Last Post: 10-02-2008, 11:07 PM
  5. Adding Arrays and Matrices
    By dlf in forum C++ Programming
    Replies: 3
    Last Post: 11-30-2005, 02:36 PM

Tags for this Thread