-4

I have the following line of code that I have to convert from C++ to C:

const MyStruct &r = pMyContext->buffer [counter];

first of all, I don’t really understand what’s going on here. I presume this line creates a new instance of the structure (r) and is filling its address with the contents of the buffer?

I’m developing a device driver, the C compiler returns:

error C2143: syntax error : missing ';' before '&'

Any Ideas?

EDIT:

In My header i have:

#define MAX_BUFFER_SIZE 40U

typedef struct {
int a;
int b;
}buffer_entry_t;

typedef struct _DEVICE_CONTEXT
{
buffer_entry_t m_tBuffer[MAX_BUFFER_SIZE];
} 
DEVICE_CONTEXT, *PDEVICE_CONTEXT;

Thanks

moonraker
  • 590
  • 7
  • 21
  • 1
    That is creating a constant *reference* to `pMyContext->buffer [counter]`. References are similar to pointers, but safer and don't require dereferencing to use them. You want to change that code to use a pointer instead. – slugonamission Jun 23 '15 at 10:32
  • `const MyStruct *r = &pMyContext->buffer [counter]; `? then i can refer to the struct via `&r->`? – moonraker Jun 23 '15 at 10:42

2 Answers2

0
const MyStruct &r = pMyContext->buffer [counter];

pMyContext is an instance of a class (assume Named class X) in C++, hopefully you can convert it as an instance of structure X. buffer is an array of MyStruct inside the class X in C++, you can convert to an array inside the MyStruct . counter is an index of the array

So you can create a const pointer to a structure MYStruct as r in C and assign array element of MyStruct with index counter of the outer structure X.

struct X pMyContext;
const MyStruct * r= pMyContext.buffer [counter];
Steephen
  • 13,137
  • 6
  • 34
  • 44
  • thanks for that. I have updated the question to include details of the header. I'm getting an error of `Error 5 error C2440: 'initializing' : cannot convert from 'buffer_entry_t' to 'const buffer_entry_t *` – moonraker Jun 23 '15 at 11:34
  • Change `const buffer_entry_t * ` to `const buffer_entry_t` – Steephen Jun 23 '15 at 13:40
0

As someone already said it is creating a constant reference to pMyContext->buffer [counter]. (more about C++ references: Reference (C++), and What is a reference )

To convert it from C++ to C, you should make it a pointer, and then instead of r.someStructMember you should write r->someStructMember, and also remember that you may need to dereference it as well (*r instead of just r).

Community
  • 1
  • 1
Giordano
  • 291
  • 2
  • 5