473,785 Members | 2,738 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help with sizeof and pointers

hello,
ok, I want to find the length of an int array that is being passed to a function:

main()
{
int array[]={1,2,3,4,5,6,7 ,8};
function(array) ;
}
function(int *array)
{
int arraylen = sizeof(*array)/sizeof(int);
}
arraylen should be 8 I get 1.

What am I doing Wrong?

Thanx
Jul 19 '05
33 12867

"Buster" <no***@nowhere. com> wrote
#define MACRO(a) (sizeof (a) / sizeof (int))


Or better,
#define MACRO(a) (sizeof (a) / sizeof * (a))

Regards.
Jul 19 '05 #11
> // Begin listing
#include <iostream>
#include <ostream>

#define MACRO(a) (sizeof (a) / sizeof (int))

template <typename T, unsigned N>
int function (T (&) [N]) { return N; }

int test (int a [])
{
// std::cout << function (a) << ", "; // compile-time error
std::cout << MACRO (a) << std::endl; // no error signaled
}

int main ()
{
int array [] = { 1, 2, 3, 4, 5, 6, 7, 8 };

std::cout << function (array) << ", ";
std::cout << MACRO (array) << std::endl;

test (array);
}
// End listing

I get what I expected on mingw32-g++ 3.2 and on bcb32:
the output is "8, 8"; "1". Both compilers report the compile
time error marked if I uncomment that line.

So the template version is slightly superior in that, although
it only works in a small set of situations, it will not compile
unless it can give you the correct answer.

It's probably only rarely that this can be used instead of the
techniques mentioned in the other replies, and even more
rarely that it will provide any significant advantage in speed
or code size. But maybe sometimes.


What happens if you do:
int main ()
{
short array [] = { 1, 2, 3, 4, 5, 6, 7, 8 };
std::cout << MACRO (array) << std::endl;
}

What if short was SomeLargeObect instead? Stroustrup advises against using
macros as they defeat the
type safety that C++ supplies. I would suggest that the template solution
is more than "slightly" superior in
that respect.
Jul 19 '05 #12
Big Brian wrote:
You need to pass the size into the function.


Or, if you can make some assumptions about the array, like what's the
last value in it ( like '\0' terminated c style char arrays ), you can
determine the length of the array.


True. That's sort of passing the size in implicitly. Passing a
std::vector (probably by reference) instead is another obvious solution,
which I didn't mention mostly because I was in a hurry. But that also
passes the size (implicitly) into the function. My statement is quite
true, but has to be taken in a very broad sense. Somehow, information
about where the array ends must be communicated to the function (and
it's not implicit in an "array argument" which is, in fact, not an array
at all).

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.

Jul 19 '05 #13
Buster wrote:
"Metzen" <an****@yahoo.c om> wrote
hello,
ok, I want to find the length of an int array that is being passed to a
function:

The following might work. I can't work out whether the standard says it does.


It absolutely will not work.

// Begin listing
#include <iostream>
#include <ostream>

#define MACRO(a) (sizeof (a) / sizeof (int))

template <typename T, unsigned N>
int function (T (&) [N]) { return N; }

int test (int a [])
The type of a is 'pointer to int'.
{
// std::cout << function (a) << ", "; // compile-time error
This didn't work because 'a' is not an array, but a pointer. You CANNOT
pass arrays to functions (directly). It always passes a pointer. Array
arguments... aren't. They are pointer arguments.
std::cout << MACRO (a) << std::endl; // no error signaled


The macro expands to

(sizeof (a) / sizeof (int))

which is equivalent to (sizeof(int*)/sizeof(int)) which does not give
the number of elements pointed to by 'a'.

I see that later you say this is the result you expected. OK, then...
but it's not an answer to the question, because it doesn't let you
determine the size of an array pointed to by a pointer argument to a
function.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.

Jul 19 '05 #14
"Kevin Goodsell" <us************ *********@never box.com> wrote in message
Buster wrote:
The following might work. I can't work out whether the standard says it does.

It absolutely will not work.
I think we're in agreement about what does and doesn't work. What I expected
to happen, happens. What I'm not sure of is whether what I expect is enforced
by the standard.
// std::cout << function (a) << ", "; // compile-time error


This didn't work because 'a' is not an array, but a pointer. You CANNOT
pass arrays to functions (directly). It always passes a pointer. Array
arguments... aren't. They are pointer arguments.


Yes, I know.
std::cout << MACRO (a) << std::endl; // no error signaled


The macro expands to

(sizeof (a) / sizeof (int))

which is equivalent to (sizeof(int*)/sizeof(int)) which does not give
the number of elements pointed to by 'a'.


Yes, I know. I recommended the template solution and showed
the older C-style technique for comparison. It's unfortunate that
I got the macro wrong, but there you go.
I see that later you say this is the result you expected. OK, then...
but it's not an answer to the question, because it doesn't let you
determine the size of an array pointed to by a pointer argument to a
function.
The question was "I want to find the length of an int array that is being
passed to a function". No mention of pointers there.
-Kevin

Jul 19 '05 #15

"Duane Hebert" <sp**@flarn.com > wrote
What happens if you do:
int main ()
{
short array [] = { 1, 2, 3, 4, 5, 6, 7, 8 };
std::cout << MACRO (array) << std::endl;
}
Implementation specific. But I should have had:
#define MACRO(a) (sizeof (a) / sizeof * (a))
which works in that situation.
What if short was SomeLargeObect instead?
The new MACRO would work just fine.
Stroustrup advises against using
macros as they defeat the
type safety that C++ supplies.
Quite right too, but type safety is not the issue here.
The decay of an array into a pointer is what makes
this macro dangerous.
I would suggest that the template solution
is more than "slightly" superior in
that respect.


"Slightly" is enough for me.

Thanks,
Buster.
Jul 19 '05 #16
Buster wrote:
"Kevin Goodsell" <us************ *********@never box.com> wrote in message
Buster wrote:
The following might work. I can't work out whether the standard says it

does.
It absolutely will not work.

I think we're in agreement about what does and doesn't work. What I expected
to happen, happens. What I'm not sure of is whether what I expect is enforced
by the standard.

// std::cout << function (a) << ", "; // compile-time error


This didn't work because 'a' is not an array, but a pointer. You CANNOT
pass arrays to functions (directly). It always passes a pointer. Array
arguments.. . aren't. They are pointer arguments.

Yes, I know.

std::cout << MACRO (a) << std::endl; // no error signaled


The macro expands to

(sizeof (a) / sizeof (int))

which is equivalent to (sizeof(int*)/sizeof(int)) which does not give
the number of elements pointed to by 'a'.

Yes, I know. I recommended the template solution and showed
the older C-style technique for comparison. It's unfortunate that
I got the macro wrong, but there you go.

I see that later you say this is the result you expected. OK, then...
but it's not an answer to the question, because it doesn't let you
determine the size of an array pointed to by a pointer argument to a
function.

The question was "I want to find the length of an int array that is being
passed to a function". No mention of pointers there.

You may be passing an array, but by the time the function you're
calling sees it, it has decayed into a pointer.

HTH,
--ag
--
Artie Gold -- Austin, Texas

Jul 19 '05 #17
> > The question was "I want to find the length of an int array that is being
passed to a function". No mention of pointers there.

You may be passing an array, but by the time the function you're
calling sees it, it has decayed into a pointer.

Not if you pass the array by reference.

Regards,
Buster.
Jul 19 '05 #18
Buster wrote:
The question was "I want to find the length of an int array that is being
passed to a function". No mention of pointers there.


You may be passing an array, but by the time the function you're
calling sees it, it has decayed into a pointer.


Not if you pass the array by reference.


OK, I'm intrigued.
Example code?

Cheers,
--ag

--
Artie Gold -- Austin, Texas

Jul 19 '05 #19
"Artie Gold" <ar*******@aust in.rr.com> wrote
You may be passing an array, but by the time the function you're
calling sees it, it has decayed into a pointer.


Not if you pass the array by reference.


OK, I'm intrigued.
Example code?


I already posted some. Shane Beasley's post has examples too.

Yours,
Buster.
Jul 19 '05 #20

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

Similar topics

5
3535
by: ArShAm | last post by:
Hi there Please help me to optimize this code for speed I added /O2 to compiler settings I added /Oe to compiler settings for accepting register type request , but it seems that is not allowed and if I remove register type for "l" , time of generating codes doesn't change the original code makes some files , but I removed that section to make it simple for you to read please help me to optimize it for faster running
5
2539
by: Sona | last post by:
I understand the problem I'm having but am not sure how to fix it. My code passes two char* to a function which reads in some strings from a file and copies the contents into the two char*s. Now when my function returns, the values stored in the char* are some garbage values (perhaps because I didn't allocate any memory for them).. but even if I allocate memory in the function, on the return of this function I see garbage.. here is my...
27
4771
by: MK | last post by:
I am a newbie. Please help. The following warning is issued by gcc-3.2.2 compiler (pc Linux): ================================================================== read_raw_data.c:51: warning: assignment makes pointer from integer without a cast ================================================================== when the following piece of code was compiled. The offending statement is calloc. A similar statement in the main() function...
2
1817
by: leo2100 | last post by:
Hi, I need help with this program. The program is supposed to take a text file and identify the words in it, then it should print them and count how many times a word is repeated. At first main called the function wordcount, and then the function did everything including printing out the results. That worked. Now I want to make the function return an array of pointers to struct palabra so the calling function can manage the data as it...
23
2553
by: vinod.bhavnani | last post by:
Hello all, I need desperate help Here is the problem: My problem today is with multidimensional arrays. Lets say i have an array A this is a 4 dimensional static array.
9
1689
by: Andreas Vinther | last post by:
I have a small piece of code that compiles but does not perform like I want it to. This code works: ---------------- void *y0; void *y1; void *y2; void *y3;
38
2609
by: James Brown | last post by:
All, I have a quick question regarding the size of pointer-types: I believe that the sizeof(char *) may not necessarily be the same as sizeof(int *) ? But how about multiple levels of pointers to the same type? Would sizeof(char **) be the same as sizeof(char *)? And if it is, would the internal representation be the same in both cases? background on this: I'm writing a simple IDL compiler that produces 'C'
4
2506
by: Christian Maier | last post by:
Hi After surfing a while I have still trouble with this array thing. I have the following function and recive a Segmentation fault, how must I code this right?? Thanks Christian Maier
3
1433
by: Jim | last post by:
Ok, I'm having 'fun' with pointers to structures. I've got some code that looks something like this: ==================== typedef struct { unsigned long *clno, *lastHistoryRecord; } aRecord;
9
1934
by: xiao | last post by:
It always dumped when I tried to run it... But it compiles OK. What I want to do is to do a test: Read information from a .dat file and then write it to another file. The original DAT file is like this : (very simple..........) 010001010110001101010101010101010101010101 #include<stdio.h>
0
9480
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10147
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9947
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8971
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7496
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5380
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4046
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2877
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.