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 33 12864
Metzen wrote: hello, ok, I want to find the length of an int array that is being passed to a function:
You can't pass an array to a function, at least not directly. main()
int main()
There is no "implicit int" rule in C++, and there hasn't been for many
years.
{ int array[]={1,2,3,4,5,6,7 ,8}; function(array) ;
This passes a pointer to the function.
} function(int *array)
'array' is a somewhat misleading name for a pointer.
{ int arraylen = sizeof(*array)/sizeof(int);
sizeof(*array) == sizeof(int), so of course you get 1 here. But no
matter what you do, you won't get the size of the memory pointed to by
'array' using sizeof.
}
arraylen should be 8 I get 1.
What am I doing Wrong?
You need to pass the size into the function.
-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.
You have two choices either end your array with a unque int or pass the
size.
main()
{
int array[]={1,2,3,4,5,6,7 ,8};
function (array, sizeof(array)/sizeof(int))
}
function(int *array, int size)
{
}
"Metzen" <an****@yahoo.c om> wrote in message
news:4e******** *************** ***@posting.goo gle.com...
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
Steven C. wrote: You have two choices
Please don't top-post. Re-read section 5 of the FAQ for posting guidelines. http://www.parashift.com/c++-faq-lite/
-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.
In article <4e************ **************@ posting.google. com>,
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:
You can't. You have to pass in the length as a separate
argument/parameter.
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?
You're using arrays instead of vectors.
#include <vector>
using namespace std;
void function (vector<int>& array)) // functions in C++ must have
// return types
{
int arraylen = array.size();
}
int main () // according to the C++ standard, main() must return an int.
{
vector<int> array(8);
array[0] = 1;
array[1] = 2;
// etc.
function (array);
return 0;
}
--
Jon Bell <jt*******@pres by.edu> Presbyterian College
Dept. of Physics and Computer Science Clinton, South Carolina USA
Metzen escribió: ok, I want to find the length of an int array that is being passed to afunction: 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?
You are using sizeof (*array), * array is equivalent in this case to
array [0], that is, an int, then you are dividing sizeof (int) by sizeof
(int).
You need something like sizeof (array) / sizeof (int), if what you
intend is obtain the number of elements in the array. Or better yet,
sizeof (array) / sizeof (* array), that will no require change if you
later change your mind and use an array of double, for example.
Regards.
> 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.
-Brian
Julián Albo escribió: 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? You are using sizeof (*array), * array is equivalent in this case to array [0], that is, an int, then you are dividing sizeof (int) by sizeof (int). You need something like sizeof (array) / sizeof (int), if what you intend is obtain the number of elements in the array. Or better yet, sizeof (array) / sizeof (* array), that will no require change if you later change your mind and use an array of double, for example.
Ops, I don't see you passed array to a function. In that case sizeof
array will give you the size of a pointer, not the size of the array.
Regards.
"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.
// 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.
Yours,
Buster. an****@yahoo.co m (Metzen) wrote in message news:<4e******* *************** ****@posting.go ogle.com>... function(int *array) { int arraylen = sizeof(*array)/sizeof(int);
That's the size of a pointer divided by the size of the object to
which it points, the result of which is meaningless.
}
arraylen should be 8 I get 1.
What am I doing Wrong?
You're passing a pointer, not an array. Technically, in modern C++,
you can fix the problem by passing an array by reference like this:
#include <cstddef>
// the size of an array is most properly represented by std::size_t
template <std::size_t N>
void function (int (&array) [N]) {
std::size_t arraylen = N;
}
However, that most people don't write functions like this. Rather,
they just pass in the size themselves:
void function (int *array, std::size_t arraylen) { }
function(array, sizeof(array) / sizeof(array[0]));
Perhaps you can combine the approaches:
template <typename T, std::size_t N>
std::size_t size (T (&) [N]) { return N; }
template <typename T, std::size_t N>
std::size_t size (const T (&) [N]) { return N; }
function(array, size(array));
- Shane This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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
|
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...
|
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...
|
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...
|
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.
| |
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;
|
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'
|
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
|
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;
|
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>
|
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,...
| |
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...
|
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
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...
|
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...
|
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 then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
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
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
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...
| |