-1

I am trying to program a microcontroller to be able to communicate with external flash memory chip which utilizes SPI. The operation code (opcode) followed by address bytes then data bytes has to be sent in order. Instead of defining these bytes each time for different commands I want to create a structure which holds this specific order. Also I want to change the whole array inside the struct.

I have tried to create structure which has three members like opcode, address and data.

void main (void)
{
//Defining Structure
struct Command_order {
    unsigned char opcode;
    unsigned char address[3];
    unsigned char data[5];
 };

 while(1)
 {
   struct Command_order temp = {0x02, {0x00,0x17,0x00} , {0x01,0x02,0x03,0x04,0x05}}; //Initialization of structure

   temp.address = {0x1F,0x03,0xC2}; //Trying to change only address 

 }
}

However this won't work, Do I get structure idea wrong or is it syntax. I am new to the concept.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
John Lenon
  • 13
  • 2
  • Either set the array cells one at a time or use a fill/copy method like `memcpy`. In C arrays are not modifiable lvalues. They cannot appear on the left side of an assignment operation as you're doing. – WhozCraig Jul 10 '19 at 16:11

2 Answers2

1

You cannot assign to an array as a whole. You need to assign to each array element.

temp.address[0] = 0x1F;
temp.address[1] = 0x03;
temp.address[2] = 0xC2;
dbush
  • 205,898
  • 23
  • 218
  • 273
1

Arrays do not have the assignment operator. You have to copy elements of one array into another array.

To do so you can use for example a compound literal and the standard function memcpy declared in header <string.h>.

Here is a demonstrative program

#include <stdio.h>
#include <string.h>

int main( void )
{
    struct Command_order 
    {
        unsigned char opcode;
        unsigned char address[3];
        unsigned char data[5];
    };    

    struct Command_order temp;

    memcpy( temp.address, ( unsigned char[] ) { 0x1F, 0x03, 0xC2 }, 3 * sizeof( unsigned char ) );
}    

Or you can rewrite the call of memcpy in the following way if the number of initializers is equal to the number of elements in the array

memcpy( temp.address, ( unsigned char[] ) { 0x1F, 0x03, 0xC2 }, sizeof( temp.address ) );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335