Pages: [1]   Go Down
Author Topic: sizeof() problem  (Read 588 times)
0 Members and 1 Guest are viewing this topic.
Cheltenham, England
Offline Offline
Newbie
*
Karma: 0
Posts: 21
Arduino Fiend
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Hi folks,

Code:
int variables[5] = {a,b,c,d,e};
Serial.println( sizeof(variables) );

Why does this block of code return 10?

Thanks in advance for your help.
Logged

0
Offline Offline
Faraday Member
**
Karma: 8
Posts: 2526
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Because you have an array of 5 ints which are two bytes each.  5*2 = 10.

-j

Logged

Cheltenham, England
Offline Offline
Newbie
*
Karma: 0
Posts: 21
Arduino Fiend
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Ahhhh that explains it... so is there a function to return how long an array is?

.. I think I'll start using char[] arrays seeing as the PWM pins only have 256-bit resolution. integers just seem too wasteful now.

Cheers!
Logged

0
Offline Offline
Faraday Member
**
Karma: 8
Posts: 2526
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I think there was a discussion on that not too long ago, but I think sizeof(a)/sizeof(a[0]) will do it.

-j

Logged

Connecticut, US
Offline Offline
Edison Member
*
Karma: 2
Posts: 1036
Whatduino
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Code:
#define countof(a)   ( (sizeof(a) / sizeof(*(a)) )

I usually define this early on.  Then you can use countof(myarrayname) and get the number of elements in the array.  Note that you cannot tell how big an array is if you use a pointer instead.
Logged

Cheltenham, England
Offline Offline
Newbie
*
Karma: 0
Posts: 21
Arduino Fiend
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

ok, thanks for the ideas folks
Logged

Pages: [1]   Go Up
Jump to: