I cannot get the size of the array after passing it to a function in C++

In summary: Ar) will evaluate to the address of the first element (index 0) of the array. sizeof(Ar[0]) evaluates to the size of what's stored at that memory location. It's pretty much a coincidence that both expressions evaluate to 4. So, back to your original question. The debugger does not lie, it tells you the truth. In the debugger, you'll see that the idNums array is 80 bytes (4 bytes for each of the 20 elements). The Ar parameter is an int * (pointer to int) and is 4 bytes.
  • #1
yungman
5,718
241
I have a strange problem. I pass an Array[20] to a function. When I put cout << sizeof(Ar); (line 29 in the program) it only shows the length of one element ( 4bytes). BUT if I write cout << Ar[10]; (line 30 in the program) It will give me the correct number of the original idNum[10]. I tried a few and it works. Obviously the idNum has successfully passed to the function. But I cannot get the size.
C++:
#include <iostream>
using namespace std;

void binarySearch(int[], int);//Function 
const int size = 20;

int main()
{    
    //Array with employee IDs sorted in ascending order.
    int idNums[] = { 101, 142, 147, 189, 199, 207, 222,
                    234, 289, 296, 310, 319, 388, 394,
                    417, 429, 447, 521, 536, 600 };

    int Hid; // to hold search result
    Hid = { sizeof(idNums) / sizeof(idNums[0])  };
    cout << " Size of idNums = " << Hid << "\n\n";
    binarySearch(idNums, Hid);
    cout << " Size of idNums after calling the function = " << sizeof(idNums) << "\n\n";
    for (int i = 0; i < 20; i++)
        cout << idNums[i] << " ";
    cout << "\n\n";

    return 0;
}

void binarySearch(int Ar[], int Last)
{
    Last = 0;
    cout << " Size of Ar = " << sizeof(Ar) << "\n\n";
    cout << " Ar[10] = " << Ar[10] << "\n\n";
    for (int index = 0; index < 20; index++)
        Ar[index] *= 2; // double the value.

}

I even put a multiply by 2 in the function so all the values are doubled before return. You can see in line 19 that I display the content of idNum and show that the value doubled. So the passing the parameters are working. I checked a lot of times, I can't figure this out. Please advice.

Also, when I pass an array to function, I have to at least put another int number or VS will flag an error. Why? eg binarySearch(idNums, Hid);

Thanks
 
Last edited:
Technology news on Phys.org
  • #2
You didn't pass an array. You passed a pointer to the array.
 
  • Like
Likes .Scott and yungman
  • #3
Vanadium 50 said:
You didn't pass an array. You passed a pointer to the array.
And more specifically, a pointer to the first element in the array.

@yungman, you have this in the notes you wrote. You must have done them in write-only mode.
Also, take a look at your code in the debugger when you run it. In main(), sizeof(idNums) will evaluate to the number of bytes allocated for the array. In your binarySearch() function, sizeof(Ar) will evaluate to 4 (bytes), the size of a pointer.
 
Last edited:
  • Like
Likes yungman
  • #4
Vanadium 50 said:
You didn't pass an array. You passed a pointer to the array.
Thanks for the reply, I understand that, that there's only one physical array. But doesn't sizeof[Ar] points right back to idNums and get the length?

I don't recall that anything passed by reference cannot be measured the size in the function. Maybe I should experiment with this.

Thanks
 
  • #5
yungman said:
I understand that, that there's only one physical array. But doesn't sizeof[Ar] points right back to idNums and get the length?
The Ar parameter is an address; ;namely the address of the actual parameter idNums. Since Ar is just an address, sizeof(Ar) evaluates to the size of a pointer, 4 bytes.
yungman said:
I don't recall that anything passed by reference cannot be measured the size in the function.
It depends on whether it's a reference to a scalar variable (such as int, char, float, etc.) or an array. For scalar variables, sizeof evaluates to the correct number of bytes.
 
  • Like
Likes harborsparrow and yungman
  • #6
Mark44 said:
And more specifically, a pointer to the first element in the array. @yungman, you have this in the notes you wrote. You must have done them in write-only mode.
Also, take a look at your code in the debugger when you run it. In main(), sizeof(idNums) will evaluate to the number of bytes allocated for the array. In your binarySearch() function, sizeof(Ar) will evaluate to 4 (bytes), the size of a pointer.
Thanks

I was being too smart, I was thinking why do I need to pass the size of the array to the function, I can get the length by length = sizeof(Ar)/sizeof(Ar[0]). So both sizeof(Ar) and sizeof(Ar[0]) will return 4bytes of the address?

Thanks
 
  • #7
Mark44 said:
The Ar parameter is an address; ;namely the address of the actual parameter idNums. Since Ar is just an address, sizeof(Ar) evaluates to the size of a pointer, 4 bytes.
It depends on whether it's a reference to a scalar variable (such as int, char, float, etc.) or an array. For scalar variables, sizeof evaluates to the correct number of bytes.
Ha, that's confusing, a variable passed by reference can be measure! But anyway, it is what it is, I just have to add to my notes.

thanks
 
  • #8
yungman said:
So both sizeof(Ar) and sizeof(Ar[0]) will return 4bytes of the address?
No, that's not quite right. sizeof(Ar) evaluates to the address of the first element (index 0) of the array. sizeof(Ar[0]) evaluates to the size of what's stored at that memory location. It's pretty much a coincidence that both expressions evaluate to 4.
yungman said:
Ha, that's confusing, a variable passed by reference can be measure!
According to what documentation? There's nothing in C or C++ that says that. There's a difference between a scalar variable passed by reference, and an address being passed. Passing by reference really is passing an address. If you pass an int, say, by reference, sizeof works as expected, since the address is just the address of a single int. Passing an array address is different, because the called function has no idea how many elements are stored at that address, only that the things stored are whatever type the array is. Except for C strings, (null-terminated character strings), you pretty much always need to pass the size of any array. Possible exceptions are arrays with some sort of sentinel that marks the end of the array, but this situation is rare.
 
  • Like
Likes harborsparrow and yungman
  • #9
Mark44 said:
No, that's not quite right. sizeof(Ar) evaluates to the address of the first element (index 0) of the array. sizeof(Ar[0]) evaluates to the size of what's stored at that memory location. It's pretty much a coincidence that both expressions evaluate to 4.
According to what documentation? There's nothing in C or C++ that says that. There's a difference between a scalar variable passed by reference, and an address being passed. Passing by reference really is passing an address. If you pass an int, say, by reference, sizeof works as expected, since the address is just the address of a single int. Passing an array address is different, because the called function has no idea how many elements are stored at that address, only that the things stored are whatever type the array is. Except for C strings, (null-terminated character strings), you pretty much always need to pass the size of any array. Possible exceptions are arrays with some sort of sentinel that marks the end of the array, but this situation is rare.
I thought you implied that. When you pass the variable by reference, you only get the address of the variable, not the content. So by your logic, when you do sizeof(variable) passed by reference inside the function, you get the address and you are reading the address of the variable.
 
  • Like
Likes harborsparrow
  • #10
I have another question off this subject, I was just talking to my grandson that is 3rd year in CS major, he said I should learn Java as it's important. Is that so? He said it's good for gaming program also.
 
  • #11
yungman said:
I thought you implied that. When you pass the variable by reference, you only get the address of the variable, not the content. So by your logic, when you do sizeof(variable) passed by reference inside the function, you get the address and you are reading the address of the variable.
What you say seems reasonable, but the semantics of references in C++ don't work that way. You actually get access to what's at the address, which is different from how pointers work -- that is, you have to use the pointer dereference operator, *, to get access to the memory pointed to. Here's an example.
C++:
#include <iostream>
using std::cout;

void fn(double & dVal, int arr[]);

int main() {
    double val = 3.2;
    int Arr[] = { 1, 3, 5 };
    fn(val, Arr);    
}

void fn(double & dVal, int arr[])
{
    cout << "Size of dVal: " << sizeof(dVal) << '\n';
    cout << "Size of arr: " << sizeof(arr) << '\n';
}
The output is
Code:
Size of dVal: 8
Size of arr: 4

If you change the declaration of the function to void fn(double * pDub, int arr[]); and actually pass the address of the double variable, then what you get for sizeof is the size of the pointer, not the size of the variable it points to.

yungman said:
I have another question off this subject, I was just talking to my grandson that is 3rd year in CS major, he said I should learn Java as it's important. Is that so?
My personal opinion is that you should stick with C++. Also, I think Java is "too easy," and many universities are doing their students a disfavor by stressing Java over C++, precisely for that reason. Here's a link to a blog by Joel Spolsky, titled "The Perils of Java Schools" - https://www.joelonsoftware.com/2005/12/29/the-perils-of-javaschools-2/
 
  • Like
Likes yungman
  • #12
Mark44 said:
What you say seems reasonable, but the semantics of references in C++ don't work that way. You actually get access to what's at the address, which is different from how pointers work -- that is, you have to use the pointer dereference operator, *, to get access to the memory pointed to. Here's an example.
C++:
#include <iostream>
using std::cout;

void fn(double & dVal, int arr[]);

int main() {
    double val = 3.2;
    int Arr[] = { 1, 3, 5 };
    fn(val, Arr);  
}

void fn(double & dVal, int arr[])
{
    cout << "Size of dVal: " << sizeof(dVal) << '\n';
    cout << "Size of arr: " << sizeof(arr) << '\n';
}
The output is
Code:
Size of dVal: 8
Size of arr: 4

If you change the declaration of the function to void fn(double * pDub, int arr[]); and actually pass the address of the double variable, then what you get for sizeof is the size of the pointer, not the size of the variable it points to.

My personal opinion is that you should stick with C++. Also, I think Java is "too easy," and many universities are doing their students a disfavor by stressing Java over C++, precisely for that reason. Here's a link to a blog by Joel Spolsky, titled "The Perils of Java Schools" - https://www.joelonsoftware.com/2005/12/29/the-perils-of-javaschools-2/
I definitely going to finish C++, there's 12 chapters I need to study( I think it's more than the first class already). I already on Chapter 8. I'd be a fool not to finish C++ first. I am more thinking about what's next. I expect I should complete the first class of C++ before Christmas.

There is no particular end on my learning, it's just learn until I get tired of it. My last hobby designing high end hifi power amps lasted over 4 years, I don't see this will be shorter. It takes time to become good at it, more than one language.I am at at pointers yet, it will be in chapter 9...Next one.
 
Last edited:
  • #13
I am happy, this is the program I wrote all by myself in binary search. This include format the display with setw(), left to make the table looks good, calling functions with reference parameter passing. It is kindergarten for you guys, but I did it without reading the example in the book. My binary search is a little longer, but I like it better as it's clearer. I have no question, it works.
C++:
// List of books for orders
#include <iostream>
#include <iomanip>
using namespace std;

void getProdNum(int &);
void Bsearch(int[], int size, int num, int &);
void displayProd();
const int Row = 9, ProdCol = 31;
char Prod[Row][ProdCol] = { {"Six Steps to Leadership"}, {"Six Steps to Leadership"}, {"Road to Exellence"},
                {"Seven Lessons of Quality"},{"Seven Lessons of Quality"},{"Seven Lessons of Quality"},
                {"Teams Are Made, Not Born"}, {"Leadership for the Future"}, {"Leadership for the Future"} };

char Desc[Row][ProdCol] = { {"Book"}, {"Audio CD"}, {"DVD"},
                {"Book"}, {"Audio CD"}, {"DVD"},
                {"Book"}, {"Book"}, {"Audio CD"} };

float Price[] = { 12.95, 14.95, 18.95, 16.95,
                21.95, 31.95, 14.95, 14.95, 16.95 };

int pnAr[] = { 914, 915, 916, 915, 918,//   0, 1, 2, 3, 4
              919, 920, 921, 922 };//        5, 6, 7, 8

int main()
{
    char key = 'A';
    while (key != '\n')// option to do it again
    {
        int partNum;// part number of the book from customer.
        int size = 9, index = -1;
        displayProd();//Show all the tittles of the items
        getProdNum(partNum);// Read what the customer choose
        cout << " The part number you enter is " << partNum << "\n\n";
        Bsearch(pnAr, size, partNum, index);// Searh for the item with part number.
        cout << " Index = " << index << "\n\n";
        if (index == -1)//-1 means the part number entered is not correct
            cout << " You enter an invalid part number, please try again. \n\n";
        else
        {
            cout << " You chose     " << left << setw(35) << Prod[index] << left << setw(15) <<
            Desc[index] << left << setw(10) << pnAr[index] << "$" << Price[index] << "\n\n";//Confirm the item chose and the price
        }
        cin.ignore(255, '\n');
        cout << " Enter any key if you want to choose again. Hit ENTER if you want to quit.";
        cin.get(key);
    } // end while
    cout << " You chose to quit, goodbye.\n\n";
    return 0;
}

void displayProd()// display the table of selections and price.
{
    for (int line = 0; line < Row; line++)
    {
        
        cout << "  " << left << setw(35) << Prod[line] << left << setw(15) <<
         Desc[line] << left << setw(10) << pnAr[line] << "$" << Price[line] << "\n\n";
    }
}

void getProdNum(int &pn)//get the part number
{
    cout << " Enter part number you wish to buy "; cin >> pn;
    cout << "\n";
}

void Bsearch(int Ar[], int size, int num, int &index)//search the part.
{
    
        int  H, M, L = 0, i = 0;
        bool done = false; // Not done yet
        H = size - 1;// array of 20, the last index Hid is 19
        while (((H - L) >= 2) && !done && i < 10)//repeat down to 2 items
        {
            i++;
            M = (L + H) / 2; //get the mid index    
            if (num == Ar[M])
            {
                index = M;// value = Ar[Mid]
                done = true;
                cout << " i = " << i << " L = " << L << ", M = " << M << ", H = " << H << ", Ar[M] = " << Ar[M] << ", val = " << num << "  index = " << index << "\n\n";
            }
            else if (num > Ar[M])
            {L = M;}
            else
            {H = M;}
        }// End while
        if (!done && num == Ar[L])
        {index = L;    done = true;}
        if (!done && num == Ar[H])
            {index = H;    done = true;}
}
 
  • #14
Once you move onto structures and classes, you will discover better ways of organizing this data.
 
  • Like
Likes yungman
  • #15
.Scott said:
Once you move onto structures and classes, you will discover better ways of organizing this data.
That's in later chapters.
 
  • #16
Java is well worth learning. It runs on a virtual machine and thus is much easier to deal with than C or C++, and it is still widely in use. Further, if you learn Java, you will be pretty close also to knowing C#, as they are similar. Learn either Java or C# for sure; they have qualities that a freer language such as Python does not have. C#, in particular, has very high performance these days, as well as extensive libraries and it now includes pretty much every advanced language feature that exists. You don't have to use any of these advanced features, but it is on a par in performance with C++ these days and is much more like to be portable across machines than a C++ program.
 
  • #17
harborsparrow said:
Java is well worth learning. It runs on a virtual machine and thus is much easier to deal with than C or C++
In what way does running on a virtual machine make Java easier to deal with? It doesn't make any difference to the programmer.

harborsparrow said:
Further, if you learn Java, you will be pretty close also to knowing C#, as they are similar.
In what way is Java similar to C#, in contrast to C++ which the OP is already studying?

harborsparrow said:
[C#] is much more like to be portable across machines than a C++ program.
No it isn't. Given that you have not provided any evidence to support your statement then I am not going to provide any evidence to support mine.
 
  • #18
All I can say is, pbuk, you are showing your ignorance. If you would like to debate these matters, please start a thread and I will indulge you.
 
  • #19
harborsparrow said:
All I can say is, pbuk, you are showing your ignorance. If you would like to debate these matters, please start a thread and I will indulge you.

That's not how it works. If you make claims, and you are asked to back them up, you back them up. I find your claims as dubious as @pbuk does. AFAIK the set of platforms for which C++ compilers exist is a superset of the set of platforms for which C# support (or Java support, for that matter) exists.
 
  • #20
I almost stopped using Physics Forums altogether because of what I perceived to be a widespread prejudice against object oriented platforms such as Java and C#. I have neither the time nor energy to defend these claims to someone who obviously doesn't understand what he or she is talking about.

I will say this much. Java and C# are in the group of languages that use much the same syntax as C and C++. Java and C# are immensely easier for beginner programmers because they have automatic garbage collection, and they run on virtual machines which hide the details of the hardware architecture from the programmer. An integer in Java is always the same size, no matter what machine it's on, unless you do something to change that explicitly. They are strongly typed, and usually won't let you accidentally put the wrong kind of thing in the wrong bucket and get a dangerous implicit conversion that screws up your results. It is pretty much impossible to cause a segmentation fault or crash a computer using either Java or C#; the same cannot be said for C and C++.

And--I can't speak for Java--but it is pretty easy with Google to verify that C# is both standardized, available on most common platforms, and is tuned these days to be very high performing, making it fine for use in high performance applications. It also offers enormously productive libraries and free IDE tools which can increase a programmer's output and reduce their errors.

Finally, it is extremely easy, once you know Java or C#, to move to the other language. Their capabilities and libraries are almost identical. The IDE's tend to be quite different though, and there formerly was a culture war between the two, which has largely died down. Java was initially ascendant but then Oracle bought it and screwed with it, and Microsoft got its act together and did a lot of good stuff and offered its tools for free, and I would say now that C# is actually better.

Anyone who is not up on computer science enough to know these basic facts should not be posting here as if they are an expert. I taught computer architecture for many years, and also, I worked in industry since the 1970's and have used almost every programming language except, oddly, Python which I never got around to. And I've made it a point to learn this stuff. I cut my teeth on C and C++ while working at Bell Labs in the 1980's. So, I feel pretty comfortable with my claims.
 
Last edited:
  • #21
harborsparrow said:
I almost stopped using Physics Forums altogether because of what I perceived to be a widespread prejudice against object oriented platforms such as Java and C#.

Unless you are going to give references to specific posts/threads that gave you that perception, it carries no weight here.

harborsparrow said:
I have neither the time nor energy to defend these claims to someone who obviously doesn't understand what he or she is talking about.

Then we have neither the time nor the energy to deal with your posts in this thread. So you have now been banned from further posting in this thread.

harborsparrow said:
Anyone who is not up on computer science enough to know these basic facts should not be posting here as if they are an expert.

Your personal opinions are not the same as "basic facts". We all know the basic facts about Java and C#. You made claims that go beyond those basic facts, and those were what you were asked to back up.

If you had just responded to @pbuk originally with the second, third, and fourth paragraphs of your post #20, there would have been no problem. People can have different opinions about languages, and there's nothing wrong with stating them--as opinions. But that's not what you did in the first and last paragraphs of your post #20, or in your post #18. Please bear that in mind for future threads.

harborsparrow said:
I feel pretty comfortable with my claims.

That doesn't mean much given that you make claims about Python when you admit you have never used it.
 

What is the reason for not being able to get the size of an array after passing it to a function in C++?

When an array is passed to a function in C++, it is converted into a pointer to its first element. This means that the function only receives a memory address and has no information about the size or length of the original array.

Can I pass the size of an array to a function in C++?

Yes, you can pass the size of an array as a separate argument to a function. This way, the function will have access to both the array and its size, allowing you to perform operations on the array with the correct length.

Is there a way to get the size of an array after it has been passed to a function in C++?

No, there is no way to get the size of an array after it has been passed to a function in C++. The only way to access the size of an array inside a function is to pass it as a separate argument or use a global variable.

Can I use the sizeof operator to get the size of an array after it has been passed to a function in C++?

No, the sizeof operator only works on variables and not on pointers. Since an array passed to a function is converted into a pointer, the sizeof operator will only return the size of the pointer and not the size of the original array.

How can I work around not being able to get the size of an array after passing it to a function in C++?

One way to work around this limitation is to use a standard library container, such as std::vector or std::array, which stores the size of the array internally and can be accessed by the function without the need for a separate argument. Another option is to use a global variable to store the size of the array and access it from within the function.

Similar threads

  • Programming and Computer Science
Replies
5
Views
885
  • Programming and Computer Science
2
Replies
65
Views
5K
  • Programming and Computer Science
Replies
32
Views
2K
Replies
10
Views
960
  • Programming and Computer Science
Replies
23
Views
1K
  • Programming and Computer Science
2
Replies
39
Views
3K
  • Programming and Computer Science
Replies
12
Views
1K
  • Programming and Computer Science
2
Replies
36
Views
2K
  • Programming and Computer Science
3
Replies
75
Views
4K
  • Programming and Computer Science
2
Replies
35
Views
2K
Back
Top