sizeof() treats static arrays as pointers

Posted By: Dark_samurai

sizeof() treats static arrays as pointers - 01/20/14 21:49

Hi JCL,

I just noticed the following behavior:

Code:
#include <acknex.h>

short test;
short array[20];

typedef struct TESTSTRUCT
{
	short array[20];
}TESTSTRUCT;

TESTSTRUCT teststruct;

void main()
{
	error(str_for_num( NULL, sizeof(test) ) );			// 2 -> OK
	error(str_for_num( NULL, sizeof(array) ) );			// 4 -> NOK
	error(str_for_num( NULL, sizeof(teststruct) ) );	// 40 -> OK
}



The seconds sizeof() statemant should return 40. Or am I wrong?
Posted By: jcl

Re: sizeof() treats static arrays as pointers - 01/21/14 08:11

In lite-C, sizeof() is a macro, not a function. It returns the size of the variable type, not of the whole array.
Posted By: WretchedSid

Re: sizeof() treats static arrays as pointers - 01/21/14 13:22

That's nice, Dark_samurai is right though. The sizeof operator in the second example should result in 40.

The wording in the standard is crap, but it clearly says that array sizes are returned. The relevant quote:

Quote:

When applied to an operand that has array type, the result is the total number of bytes in the array.

(Section 6.5.3.4)

Pointers on the other hand don't count as arrays as far as the standard is concerned, so if it were a pointer, it should return 4.
Posted By: Dark_samurai

Re: sizeof() treats static arrays as pointers - 01/21/14 16:18

I don't think it's good to have this difference to normal C in such a basic functionality. Just imagine someone who used C already for some time and then switches to Lite-C because he wants to make games now. He writes some code and he will soon run into serious problems because sizeof works different. And the problem will be most likely some memory related crashes which sometimes may occur or may not (we all know this kind of problems I think).
And to say the truth, if your code has a problem, I think the last thing you would check is if sizeof is working correctly ^^

Thats why in my opinion, this is a serious problem...

Edit: Thanks Sid for searching the according paragraph in the standard!
Posted By: jcl

Re: sizeof() treats static arrays as pointers - 01/21/14 18:32

You certainly have a point. I'll put a real sizeof() function on my list.
Posted By: Dark_samurai

Re: sizeof() treats static arrays as pointers - 01/22/14 15:15

Thanks laugh
Posted By: DarkProgrammer

Re: sizeof() treats static arrays as pointers - 05/26/14 06:57

I had the same issue with the sizeof() command, so, I did a forum search & found this thread. Is there a "work around" for this problem?
Posted By: jcl

Re: sizeof() treats static arrays as pointers - 05/26/14 08:21

Sure, always #define static array sizes. This should be a programmer habit anyway. You'll also need it for loops on that array.

#define MYLENGTH 20

short array[MYLENGTH];

...

int arraysize = MYLENGTH*sizeof(short);
© 2024 lite-C Forums