Damodaran Damodaran - 2 months ago 6
C Question

Array of struct modify with pointer

I wanna function to modify each element of array of structure with pointer.

I am using two different size arrays

struct color
{

char red;
char blue;
int white;
};

struct colorInit
{

char red;
char blue;
int white;
int padding[60];
};


struct color batch1[30];

struct colorInit batchInitializd[30];

void modifystruct ( struct color *ptr)

{

for ( int i = 0; i < 30; i++)

{

ptr[i].red = batchInitializd[i].red;

ptr[i].white = batchInitializd[i].white;

ptr[i].blue = batchInitializd[i].blue;

}

}


am i using pointer right way in the function ?

Answer

am i using pointer right way in the function ?

Syntactically speaking, yes.

The function will work fine if ptr points to an array of 30 or more objects. Otherwise, it will have undefined behavior.

The following is not valid any more since the OP changed the object type of batchInitializd.

You can simplify the function to:

void modifystruct(struct color *ptr)
{
   for ( int i = 0; i < 30; i++)
   {
      ptr[i] = batchInitializd[i];
   }
}