views:

162

answers:

2

I have a typedef:

typedef unsigned char MyType[2];

I pass it to a function and the result is FAIL!

void f(MyType * m)
{
*m[0] = 0x55;
*m[1] = 0x66;
}

void main(void)
{
Mytype a;
a[0] = 0x45;
a[1] = 0x89;

f(&a);
}

The manipulation of variable a in main() works on 1 byte indexing, so a is equal to {0x45, 0x89}. However in function f the indexing acts on 2 bytes (the sizeof the type).

So in function f, *m[1] in this instance is actually modifying memory out of bounds.

Why is this, what have I forgotten?

Thanks.

+4  A: 

Try:

(*m)[1]

instead of *m[1]

Mehrdad Afshari
+1  A: 

Ah just worked it out after giving up! Brackets Boy, Brackets.

void f(MyType * m)
{
(*m)[0] = 0x55;
(*m)[1] = 0x66;
}

void main(void)
{
Mytype a;
a[0] = 0x45;
a[1] = 0x89;

f(&a);
}
Oliver
Why typedef in the first place? (*m)[0] is ugly.
sigjuice
I'm working on an API for an embedded application and experimenting with typedef array for public interfaces as a programming hint to the array size rather than replying on them having read the docs or using an IDE like eclipse to inform at dev time. So the untiddiness is only at the entry point in.
Oliver
It's kind of embarrassing to see this question here now - a moment of frustration / dumbness - anyway I tried it and decided it's not a good idea.
Oliver