0

i am not sure why the value of b is coming out as 0
according to me it should come out as 3

#include <iostream>
using namespace std;
void read(int a[],int n)
{
    for (int k = 0;k < n;k++)
    {
        cout << "enter the " << k << "th integer";
        cin >> a[k];
    }
}
int main()
{
    int a[] = {};
    read(a,3);
    int b = sizeof(a)/sizeof(int);
    cout << b << endl;
    return 0;
}

Edited by smrati.katiyar: n/a

3
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by VernonDozier
0

sizeof is a compile-time 'function'... it cannot get the size of dynamic arrays.
So, your code is very wrong... your intention is to write 3 items into a, but there is only space for 0 items.

0

I compiled and ran it and was surprised it compiled and ran at all. Regardless, I think you're playing with fire memory-wise. I'm not sure what this does or why you can get away with it, but I think it's just luck. There must be some default array size somewhere and that's why it works for a small number like 3. I ran this program and as expected, it crashed for a large number like 50,000.

#include <iostream>
using namespace std;
void read(int a[],int n)
{
    for (int k = 0;k < n;k++)
    {
        a[k] = 1;
    }
}
int main()
{
    int a[] = {};
    read(a,50000);
    int b = sizeof(a)/sizeof(int);
    cout << b << endl;
    return 0;
}

You need to specify an array size in line 12 for this to work.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.