473,216 Members | 1,989 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,216 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 11920
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...
1
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
0
by: VivesProcSPL | last post by:
Obviously, one of the original purposes of SQL is to make data query processing easy. The language uses many English-like terms and syntax in an effort to make it easy to learn, particularly for...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
by: jimatqsi | last post by:
The boss wants the word "CONFIDENTIAL" overlaying certain reports. He wants it large, slanted across the page, on every page, very light gray, outlined letters, not block letters. I thought Word Art...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....

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.