Thread: Problem: Allocate an array of structs within a struct.

  1. #1
    Registered User
    Join Date
    May 2021
    Posts
    1

    Problem: Allocate an array of structs within a struct.

    I'm trying to create a pixel buffer for a render bucket but I can't get my head around the pointers. Or the declaration.
    Can anyone help me sort this out?

    // I need to allocate this:
    Code:
    struct pixel {	unsigned char R;
    			unsigned char G;
    			unsigned char B; };
    in this
    Code:
    struct bucket {	long double max;
    			long double min;
    			long double factor;
    			int max_it;
    			int size;
    			int xStart;
    			int yStart;
    			struct pixel *buffer;
    			char started;
    			char done; };
    Access it in another function
    Code:
    	bucket->buffer[xl+(yl*bucket->size)].R = map(brightness*brightness, 0, 1000, 0, 155);
    	bucket->buffer[xl+(yl*bucket->size)].G = map(brightness, 0, 255, 0, 155);
    	bucket->buffer[xl+(yl*bucket->size)].B = map(brightness, 0, 255, 0, 255);
    So how do I declare and allocate it?
    Code:
    int main(int argc, char *argv[])
    {
    	struct bucket bucketlist[buckets_per_frame];
    	struct pixel* buffer[pixels_per_bucket];
    
    	for ( i=0 ; i<buckets_per_frame ; i++ )
    	{
    		for ( j=0 ; j<pixels_per_bucket ; j++ )
    		{
    			bucketlist[i].buffer[j] = (struct pixel *) malloc(sizeof(struct pixel));
    		}
    	}
    }

  2. #2
    Registered User
    Join Date
    Dec 2017
    Posts
    1,192
    Code:
    int main()
    {
        struct bucket bucketlist[buckets_per_frame];
     
        for ( int i=0 ; i<buckets_per_frame ; i++ )
        {
            bucketlist[i].buffer = malloc(pixels_per_bucket * sizeof(struct pixel));
        }
     
        // ...
     
        for ( int i=0 ; i<buckets_per_frame ; i++ )
        {
            free( bucketlist[i] );
        }
     
        return 0;
    }
    We live as it were by chance, and by chance we are governed. - Seneca

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Allocate memory for array that contains struct. Help please.
    By Grigoris Savvas in forum C Programming
    Replies: 7
    Last Post: 04-03-2012, 12:14 PM
  2. Replies: 6
    Last Post: 04-02-2012, 07:38 PM
  3. Move struct into array of structs?
    By Dest in forum C Programming
    Replies: 4
    Last Post: 05-05-2010, 10:55 AM
  4. Array of structs -> struct to void
    By v1n1c1u5 in forum C Programming
    Replies: 1
    Last Post: 12-14-2009, 07:23 AM
  5. Array of Structs, setting value of struct
    By tesla in forum C Programming
    Replies: 2
    Last Post: 09-14-2009, 09:21 AM

Tags for this Thread