Search code examples
c++arrayspointersreturnatmelstudio

Atmel Studio: Returning a register which contains an array


I am coding a project for an Arduino in Atmel Studio. In my code, I have two functions that look like the following:

unsigned char* USART_Receive(void){
    while(!(UCSR0A & (1<<RXC0)) );
    return UDR0;
}

void Transmit(){
        unsigned char *a = USART_Receive();

        unsigned char pckaffe[4] = { 0x0C, 0x0A, 0x0F, 0x0E };
        unsigned char pcpersienner[4] = { 0x0B, 0x0B, 0x0B, 0x0B }; 

        if(a == pckaffe && zeroCrossCounter() == 1){
            sendBurst();
        }
}

If everything works right, the UDR0 register should contain an array with 4 indexes (array[4]), therefore to return the array in the register, I used pointers. However, I get the following error at return UDR0:

Error invalid conversion from 'uint8_t {aka unsigned char}' to 'unsigned char*' [-fpermissive]

EDIT:

Adam Stepniak:

uint8_t varrr = 0;

unsigned char* USART_Receive(void){
    while(!(UCSR0A & (1<<RXC0)) );
    varrr = UDR0;
    return &varrr;
}

Solution

  • Quite out of context to say that it fix your whole code, but if you would do:

    #include <cstdint>
    
    uint8_t varaible = 0;
    
    unsigned char* USART_Receive(void){
        return varaible;
    }
    
    void Transmit(){
            unsigned char *a = USART_Receive();
    }
    
    int main(){
        Transmit();
    }
    

    Will will get:

    In function 'unsigned char* USART_Receive()':
    6:12: error: invalid conversion from 'uint8_t {aka unsigned char}' to 'unsigned char*' [-fpermissive]
     In function 'void Transmit()':
    10:24: warning: unused variable 'a' [-Wunused-variable]
    

    To fix this just return address of the variable:

    #include <cstdint>
    
    uint8_t varaible = 0;
    
    unsigned char* USART_Receive(void){
        return &varaible;
    }
    
    void Transmit(){
            unsigned char *a = USART_Receive();
    }
    
    int main(){
        Transmit();
    }