473,396 Members | 2,004 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Problem with calculating the size of an array

Hi, my problem with calculating the size of an array is when
I pass an array as a parameter to a function which perform the
calculation, the result never comes right, like below:

int SizeOfArray(int a[]) {
return (sizeof(a)/sizeof(a[0]));
}
main() {
int a[3]={1,2,3};
printf("%d\n",SizeOfArray(a));
}

but is right when the array declared in the same scope as the sizeof()
statment,

main() {
int a[3]={1,2,3};
printf("%d\n",sizeof(a)/sizeof(a[0]));
}

why's that ? i suspect that i passed the wrong type of parameter to
the function. (should be &a or *a or something... ??)
Nov 14 '05 #1
5 11929
ru****@sohu.com (sugaray) wrote in
news:ad**************************@posting.google.c om:
Hi, my problem with calculating the size of an array is when
I pass an array as a parameter to a function which perform the
calculation, the result never comes right, like below:

int SizeOfArray(int a[]) {
return (sizeof(a)/sizeof(a[0]));


Bang! You have tricked yourself. Although you think you are passing an
array into SizeOfArray() you are actually passing a pointer which on
32-bit platforms is often only 4 bytes in size. You can (1) pass in the
size, (2)package the array inside a struct, or (3) simply USE THE C sizeof
OPERATOR!
#include <stdio.h>

struct ArrayWrap
{
int array[100];
} pkg;

int array[100];

void printPkgArrSize(struct ArrayWrap *pPkg)
{
printf("Size of array is %u bytes\n", sizeof pPkg->array);
}

void printArrSize(size_t size)
{
printf("Size of array is %u bytes\n", size);
}

int main(void)
{
/* 1
*/
printPkgArrSize(&pkg);

/* 2
*/
printArrSize(sizeof array);

/* 3
*/
printf("Size of array is %u bytes\n", sizeof array);

return 0;
}
--
- Mark ->
--
Nov 14 '05 #2

"sugaray" <ru****@sohu.com> wrote in message
news:ad**************************@posting.google.c om...
Hi, my problem with calculating the size of an array is when
I pass an array as a parameter to a function which perform the
calculation, the result never comes right, like below:

int SizeOfArray(int a[]) {
return (sizeof(a)/sizeof(a[0]));
}
main() {
int a[3]={1,2,3};
printf("%d\n",SizeOfArray(a));
}
[..]
the function. (should be &a or *a or something... ??)


Actually, SizeOfArray () returns the number of elements
of the array. The above function would not work.
I would write the function as below, though, I would
prefer a macro to function:

#include <stdio.h>
#include <stdlib.h>

#define MAX 10

size_t
len_of_array ( int (*a)[MAX] )
{
printf ( "Array size: %lu\n", sizeof ( *a ) );
return sizeof *a / sizeof **a;
}

int
main ( void )
{
int a[MAX];
printf ( "Number of elements: %lu\n", len_of_array ( &a ) );
return EXIT_SUCCESS;
}
--
Vijay Kumar R Zanvar
My Home Page - http://www.geocities.com/vijoeyz/
Nov 14 '05 #3
nrk
Vijay Kumar R Zanvar wrote:
#include <stdio.h>
#include <stdlib.h>

#define MAX 10

size_t
len_of_array ( int (*a)[MAX] )
{
printf ( "Array size: %lu\n", sizeof ( *a ) );
return sizeof *a / sizeof **a;
}

This is equivalent to:
size_t len_of_array(void) { return MAX; }

It might be useful to define a macro:

#define NELEMS(x) (sizeof x/sizeof x[0])

and use that instead.

-nrk.
int
main ( void )
{
int a[MAX];
printf ( "Number of elements: %lu\n", len_of_array ( &a ) );
return EXIT_SUCCESS;
}


--
Remove devnull for email
Nov 14 '05 #4
"Mark A. Odell" <no****@embeddedfw.com> wrote in message news:<Xn********************************@130.133.1 .4>...
ru****@sohu.com (sugaray) wrote in
news:ad**************************@posting.google.c om:
Hi, my problem with calculating the size of an array is when
I pass an array as a parameter to a function which perform the
calculation, the result never comes right, like below:

int SizeOfArray(int a[]) {
return (sizeof(a)/sizeof(a[0]));


Bang! You have tricked yourself. Although you think you are passing an
array into SizeOfArray() you are actually passing a pointer which on
32-bit platforms is often only 4 bytes in size. You can (1) pass in the
size, (2)package the array inside a struct, or (3) simply USE THE C sizeof
OPERATOR!


or 4) implement the functionality as a macro. Use of function
macros is always to be done with some hesitation, but this
one seems OK:

#define N_ELTS(a) ((int)(sizeof(a)/sizeof(a[0])))

I put in the cast to emulate his function semantics, as he wants
to use the value as an int, not a size_t. Of course, this macro
only works if the array definition is in scope, otherwise
one of the solutions Mark proposed seems needed. In real life,
packaging the array and its size into a struct keeps all the info
in one place and that is nice... Hmmm, not having a C99 standard
at hand, what happens if this macro is applied to a VLA?
sizeof evaluated at runtime? error?

-David
Nov 14 '05 #5
Groovy hepcat sugaray was jivin' on 22 Jan 2004 05:58:12 -0800 in
comp.lang.c.
Problem with calculating the size of an array's a cool scene! Dig it!
Hi, my problem with calculating the size of an array is when
I pass an array as a parameter to a function which perform the
calculation, the result never comes right, like below:

int SizeOfArray(int a[]) {
return (sizeof(a)/sizeof(a[0]));


Why didn't you pay attention when you read the FAQ? I know you did
read it, because it is a requirement before posting to the newsgroup.
Noone wants to be thought of as an idiot, so you must have read the
FAQ. However, you obviously missed question 6.21, because you surely
would have asked for clarification had you read it and misunderstood.
So, the conclusion I'm drawing is that you just weren't paying
attention at all. You simply couldn't be bothered. Well, why should we
bother to help you, then?
If you want our help, you're going to have to prove it. You're going
to have to show us that you are looking for answers and are willing to
learn. Start by going to the FAQ's web site,
http://www.eskimo.com/~scs/C-faq/top.html, and reading it through
Then, read at least a month worth of articles in this newsgroup. Make
sure you read the article entitled "Welcome to comp.lang.c!" by James
Hu.

--

Dig the even newer still, yet more improved, sig!

http://alphalink.com.au/~phaywood/
"Ain't I'm a dog?" - Ronny Self, Ain't I'm a Dog, written by G. Sherry & W. Walker.
I know it's not "technically correct" English; but since when was rock & roll "technically correct"?
Nov 14 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

25
by: kie | last post by:
hello, i have a table that creates and deletes rows dynamically using createElement, appendChild, removeChild. when i have added the required amount of rows and input my data, i would like to...
3
by: PHil Coveney | last post by:
Hello, I am having difficulty marshalling structures when calling DeviceIoControl. I am importing this Win32 function as static extern int DeviceIoControl (int hDevice, int...
8
by: dbuser | last post by:
Hi, I need help on a problem, as described below. I am reading a file "input.txt"which has data like this: abc def gh izk lmnopq rst uvwxyz I am using fstream object to read the file and...
15
by: Peter Afonin | last post by:
Hello, I'm struggling with the string conversion to MD5 which I've never user before. I have a string that I need to encode which looks approximately like this: ...
1
by: Ray Z | last post by:
I would like to have someone to help me out with my program. Users are able to add items if they wish for the Monthly Claims Charges System. I did not manage to do the calculation part of the...
22
by: Wilson | last post by:
i am learning to program using c++ and was set a task of making a simple encryption algorithim. I choose to start with one where simply each letter is replaced with its equivilent in the alphabet...
28
Nepomuk
by: Nepomuk | last post by:
Hi! I've read, that in C++ there's no predefined method, to calculate the size of an array. However, it's supposed to work withsizeof(array)/sizeof(array)Now, this does work in some situations, but...
4
by: =?Utf-8?B?TmF2YW5lZXRoLksuTg==?= | last post by:
Say I have a class like, class Sample { public decimal first = 10; public decimal second = 20; } I have initialized it
7
by: edsunder | last post by:
I'm making a "wrapper" for an unmanaged DLL (written, I'm fairly certain in C). I have a c++ "wrapper" that I'm trying to convert to VB.net. I've got most of the program working, but I've hit a brick...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.