473,416 Members | 1,732 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,416 software developers and data experts.

How to know the size of array

Hi,

I have a question.

How can i know the size of array when it is passed to a function.
For Example i have this code:

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

void foo(int * array);

int main(void)
{
int n=5;
int array[n];

foo(array);

}

void foo(int * array)
{

/*Here how can i know the size of array without passing it explicitly*/
}
Thanx in advance

Vishal

Mar 23 '06 #1
12 112057

ma***********@gmail.com wrote:
Hi,

I have a question.

How can i know the size of array when it is passed to a function.
You can't, unless:

a) you pass it as an extra parameter
b) last element of your array is a "sentinel" value so you can
determine it at run-time (like C strings which are zero terminated).
For Example i have this code:

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

void foo(int * array);
Try:

void foo(int *array, size_t len);

int main(void)
{
int n=5;
int array[n];
Not allowed in C90. Try:

#define ARRAY_SIZE 5
int array[ARRAY_SIZE];

foo(array);
foo(array, sizeof array / sizeof array[0]);

}

void foo(int * array)
void foo(int *array, size_t len)
{
Now the array size is in `len`.

/*Here how can i know the size of array without passing it explicitly*/
}


Mar 23 '06 #2
> void foo(int * array)
void foo(int *array, size_t len)
{
Now the array size is in `len`.


Thanx for the quick reply.

I think i read somewhere that i can get the size by:

(sizeof(array) ) / (sizeof(element))

in this case it will be

(sizeof(array)) / (sizeof(int))

I am not sure about this. Can we get the sizeof array to return the
size of all its elements.
Can sizeof find where the array is getting finished or it will just
give me the size of element.

Is there no way to get the size of array without passing the its
length.

Cheers
Vishal

Mar 23 '06 #3
ma***********@gmail.com wrote:
I think i read somewhere that i can get the size by:

(sizeof(array) ) / (sizeof(element))

in this case it will be

(sizeof(array)) / (sizeof(int))


FYI:
[src = n1124.pdf]
---------------
6.5.3.4 The sizeof operator
....
Semantics
[ ...]
When applied to an operand that has array
type, the result is the total number of bytes in the array.[85]
[ ... ]
6. EXAMPLE 2 Another use of the sizeof operator is
to compute the number of elements in an array:

sizeof array / sizeof array[0]
....
[85] When applied to a parameter declared to have array or function
type, the sizeof operator yields the size of the adjusted (pointer)
type.
----------

Mar 23 '06 #4

ma***********@gmail.com wrote:
void foo(int * array)
void foo(int *array, size_t len)
{

Now the array size is in `len`.


Thanx for the quick reply.
I think i read somewhere that i can get the size by:

(sizeof(array) ) / (sizeof(element))


No. This yields the number of elements in the array, not it's size.
in this case it will be

(sizeof(array)) / (sizeof(int))

I am not sure about this. Can we get the sizeof array to return the
size of all its elements.
Can sizeof find where the array is getting finished or it will just
give me the size of element.
The sizeof operator can give the sizes of all compile time data
structures. For those that you declare at runtime, you'll have to
manage their size yourself.
Is there no way to get the size of array without passing the its
length.


As Vladimir has noted, you can use a "sentinel" value and scan through
the array for this special value to find it's length and hence it's
size. C's strings are implemented in this way.

Mar 23 '06 #5

ma***********@gmail.com wrote:
void foo(int * array)

void foo(int *array, size_t len)


{


Now the array size is in `len`.


Thanx for the quick reply.

I think i read somewhere that i can get the size by:


You could have read it in my reply as well, have you scrolled all the
way down. Do that now.
(sizeof(array) ) / (sizeof(element))
This is not the preferred syntax. See your textbook.
in this case it will be

(sizeof(array)) / (sizeof(int))
Look at my previous post, interspersed with your code.
I am not sure about this. Can we get the sizeof array to return the
size of all its elements.
Can sizeof find where the array is getting finished or it will just
give me the size of element.
Look at other replies in this thread.
Is there no way to get the size of array without passing the its
length.


Use the "sentinel" if you have a value that cannot happen otherwise. I
told you that already.

--
BR, Vladimir

Mar 23 '06 #6
ma***********@gmail.com wrote:
Hi,

I have a question.

How can i know the size of array when it is passed to a function.
For Example i have this code:

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

void foo(int * array);

int main(void)
{
int n=5;
int array[n];

foo(array);

}

void foo(int * array)
{

/*Here how can i know the size of array without passing it
explicitly*/ }


You have to pass the size of the array somehow.

#include <stdio.h>

void arr(int size, int array[size])
{
printf("%d\n", size);
}
int main(void)
{
int n = 200;

int array[n];

arr(sizeof(array) / sizeof(array[0]), array);

return 0;
}

*However*

I'd like to add a thought here - for completeness really:

I expect most replies will be along the lines of 'you must pass the size' -
usually meaning as a seperate argument to the called function [as above].
However, the necessary size 'information' may be made available in a number
of ways.

Premise: you must make the size of the array available to the called
function.

However, the size information *could* be /passed/ in /n/ number of alternate
ways - for example, there could be a 'stop element' containing a value that
signifies that the end of the array has been reached [-1 below]. But, that
would of course mean that your array cannot contain a non-stop data value
of -1 [this will act like a '\0' for a char array used as a string].
#include <stdio.h>

void arr(int array[static 1]) // or void arr(int array[])
{
for(int n = 0; array[n] != -1; ++n)
{
printf("%d ", array[n]);
}
}

int main(void)
{

int array[11] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -1};
Output: 1 2 3 4 5 6 7 8 9 10
Or, a little safer, the first element could be used to indicate the size of
the array in total [Pascal(ish)].

void arr(int array[static 1]) // or void arr(int array[])
{
for(int n = 1; n < array[0]; ++n)
{
printf("%d ", array[n]);
}
}
int main(void)
{

int array[11] = {11, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

...
Output: 1 2 3 4 5 6 7 8 9 10
I'm not sure about the legality of this, but that could be refined a little
....
#include <stdio.h>

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

void arr(int array[static 1]) // or void arr(int array[])
{
for(int n = 1; n < array[0]; ++n)
{
printf("%d ", array[n]);
}
}
int main(void)
{

int array[11] = {arr_size(array), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Of course, encoding information about the array *in* the array itself could
well be, um, *problematic* [/read/: come as an unwelcome surprise to most C
programmers], but I thought it worth chucking it it!
--
==============
Not a pedant
==============
Mar 23 '06 #7
"ma***********@gmail.com" <ma***********@gmail.com> writes:
How can i know the size of array when it is passed to a function.
For Example i have this code:

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

void foo(int * array);

int main(void)
{
int n=5;
int array[n];

foo(array);

}

void foo(int * array)
{

/*Here how can i know the size of array without passing it explicitly*/
}


You can't. sizeof() inside the function applies to the pointer, not
to the array.

Do you want the size (in bytes) or the length (in elements)?

Section 6 of the comp.lang.c FAQ, <http://www.c-faq.com/>, is likely
to be helpful.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Mar 23 '06 #8
"pemo" <us***********@gmail.com> writes:
[snip]
Or, a little safer, the first element could be used to indicate the size of
the array in total [Pascal(ish)].

void arr(int array[static 1]) // or void arr(int array[])
{
for(int n = 1; n < array[0]; ++n)
{
printf("%d ", array[n]);
}
}
int main(void)
{

int array[11] = {11, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

...

[...]

Again, it's important to distinguish between the *size* (in bytes) and
the *length* (in elements).

That approach is usable only if the element type is capable of holding
the length. For character arrays, this limits the maximum length to
255 on most systems. For non-numeric arrays, it's just not workable.

Passing a separate argument is a much more general solution.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Mar 23 '06 #9
u should pass the size of array exlicitly or place a 'NULL' value at
the end of the array.

Mar 24 '06 #10
zhou...@gmail.com wrote:
u should pass the size of array exlicitly or place a 'NULL' value at
the end of the array.


Please quote the post to which you're replying and avoid abbreviations
like 'u' for you etc. Read the following:

http://cfaj.freeshell.org/google/

NULL is a macro which expands to the null pointer constant. A sentinel
value to signal the end of an array would usually contain a null
character which is different.

Mar 24 '06 #11

ma***********@gmail.com wrote:
void foo(int * array)

void foo(int *array, size_t len)


{


Now the array size is in `len`.


Thanx for the quick reply.

I think i read somewhere that i can get the size by:

(sizeof(array) ) / (sizeof(element))

in this case it will be

(sizeof(array)) / (sizeof(int))


Given the following:

int foo[10];

sizeof foo will return the total number of bytes taken up by the whole
array, and sizeof foo[0] will return the number of bytes used by a
single array element, so yes, the expression

sizeof foo / sizeof foo[0]

will give you the number of elements (10) in the array.

Unfortunately, this won't help you if you pass the array to a function.
In most contexts*, the type of the array identifier "decays" into a
pointer to the base type, and its value is set to the address of the
first element in the array. IOW, when you write

bar(foo);

what actually gets passed to bar is a pointer type object, not an array
type object:

void bar(int *arr)
{
...
}

and sizeof arr will return the number of bytes used by the pointer,
*not* the array it points to, so the sizeof arr / sizeof arr[0] trick
won't work.

* The only times the array identifier doesn't decay into a pointer is
when it's an operand of the sizeof and unary & operators.
I am not sure about this. Can we get the sizeof array to return the
size of all its elements.
Can sizeof find where the array is getting finished or it will just
give me the size of element.

Is there no way to get the size of array without passing the its
length.
Not really, no.

Cheers
Vishal


Mar 24 '06 #12
"santosh" <sa*********@gmail.com> writes:
zhou...@gmail.com wrote:
u should pass the size of array exlicitly or place a 'NULL' value at
the end of the array.


Please quote the post to which you're replying and avoid abbreviations
like 'u' for you etc. Read the following:

http://cfaj.freeshell.org/google/

NULL is a macro which expands to the null pointer constant. A sentinel
value to signal the end of an array would usually contain a null
character which is different.


Not if it's an array of pointers. (Lacking context, I don't know what
the original array looked like.)

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Mar 24 '06 #13

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

Similar topics

12
by: Raja | last post by:
How to know the buffer size and increase buffer size in c++.
79
by: Me | last post by:
Just a question/observation out of frustration. I read in depth the book by Peter Van Der Linden entitled "Expert C Programming" (Deep C Secrets). In particular the chapters entitled: 4: The...
22
by: Wynand Winterbach | last post by:
I think every C programmer can relate to the frustrations that malloc allocated arrays bring. In particular, I've always found the fact that the size of an array must be stored separately to be a...
40
by: madireddy | last post by:
Hi, Inside a program how do i find out what size has been allocated to pointer using malloc. eg... int *p; p=(int*)malloc(1024*sizeof(int)); now how do find how much has been allocated to p?...
8
by: Phill | last post by:
Anyone know the internal working of this thing. I expected it to be kinda slow at enumerating large lists of objects but it was actually pretty good. I was able to write a quick linked list class...
13
by: lovecreatesbeauty | last post by:
/* How do free() know how many elements should be freed in a dynamic array? When free a single variable, the amount of byte of memory can be retrieved from the type of variable itself. ...
8
by: redefined.horizons | last post by:
I would like to have an array declaration where the size of the array is dependent on a variable. Something like this: /* Store the desired size of the array in a variable named "array_size". */...
2
by: Harry | last post by:
Good Day To all, When i am declaring a array for e.g char ....it means i am declaring array of 45 characters each of which has a maximum,minimum value limit or range...for example in...
5
by: desktop | last post by:
I have a function that takes two pointers to an array. The first point to the first element while the other points to the last element. int nums = { 1, 2, 3, 4, 5, 7, 8, 9}; int* result; int...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
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
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,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

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.