Peder
Peder

Reputation: 345

Simple C struct won't compile

I'm trying to implement a simple ring buffer using a struct. I have never used structs before and just started to try to understand them. The compiler exits with this error:

expected '=', ',', ';', 'asm' or '__attribute__' before '.' token

The error refers to the last two lines.

#define MAX_PROCESSES 16

struct ring_buffer{
    uint8_t data[MAX_PROCESSES];
    uint8_t size;
    uint8_t count;
    uint8_t write_pos;
    uint8_t read_pos;
};

struct ring_buffer ring_buffer_processes;
ring_buffer_processes.size = MAX_PROCESSES;
ring_buffer_processes->size = MAX_PROCESSES;

I've used the to operators just for test purposes to see, if any of it works. This should of course only be one line.

I also tried using "typedef", but that doesn't help either. What is wrong here?

Thanks

Upvotes: 0

Views: 379

Answers (3)

user6427267
user6427267

Reputation: 76

In C Language,A non-pointer object Has been Accessed by using . Operator and A pointer Object has been Accessed by using -> Operator.

     #define MAX_PROCESSES 16

    struct ring_buffer{
        uint8_t data[MAX_PROCESSES];
        uint8_t size;
        uint8_t count;
        uint8_t write_pos;
        uint8_t read_pos;
    };

    struct ring_buffer ring_buffer_processes;
ring_buffer_processes. size = MAX_PROCESSES;

    struct ring_buffer *ptr_ring_buffer_processes;
*ptr_ring_buffer_processes-> size =& MAX_PROCESSES;

Upvotes: 0

Mohan
Mohan

Reputation: 1901

To access any member of a structure, we use the member access operator (.) but

To access the members of a structure using a pointer to that structure, you must use the operator.

Change the code ..

#define MAX_PROCESSES 16

struct ring_buffer{
    uint8_t data[MAX_PROCESSES];
    uint8_t size;
    uint8_t count;
    uint8_t write_pos;
    uint8_t read_pos;
};

struct ring_buffer ring_buffer_processes;

void main(){
    ring_buffer_processes.size = MAX_PROCESSES;
    //ring_buffer_processes->size = MAX_PROCESSES; Not required you can access struct variable with . operator.
}

Upvotes: 1

Sandy
Sandy

Reputation: 903

Your code has two mistakes:

  1. It is missing the entry point of execution i.e. main()
  2. It is trying to access a member using '->' which is used when accessing a member via pointer.

So correcting these points gives us:

#include <stdint.h>

#define MAX_PROCESSES 16

struct ring_buffer{
    uint8_t data[MAX_PROCESSES];
    uint8_t size;
    uint8_t count;
    uint8_t write_pos;
    uint8_t read_pos;
};

int main(void)
{
    struct ring_buffer ring_buffer_processes;
    struct ring_buffer * p_ring_buffer_processes;

    p_ring_buffer_processes = &ring_buffer_processes;
    ring_buffer_processes.size = MAX_PROCESSES;
    p_ring_buffer_processes->size = MAX_PROCESSES;

    return 0;
}

Upvotes: 3

Related Questions