Home > Enterprise >  Why does my array print more than I want?
Why does my array print more than I want?

Time:02-08

I'm trying to write an array in c , which consist of 10 integers that are all 1, unless changed through keyboard input. For some reason my code prints out way more than 10 integers and I'm not sure why.

int main()
{
    int index, value;
    int count = 0;
    int myData [10];
    for (int i = 0; i < sizeof(myData); i  )
    {
        myData[i] = 1;
    }

    do
    {
        for (int i = 0; i < sizeof(myData); i  )
        {
            std::cout << myData[i] << " ";
        }

        std::cout << "Input index: ";
        std::cin >> index;
        std::cout << "Input value: ";
        std::cin >> value;

        myData[index] = value;

    } while ((0 <= index) && (index <= sizeof(myData)));

    std::cout << "Index out of range. Exit." << std::endl;
    
    return 0;
}

EDIT I got it to work thank you :D but for some reason now I'm getting a buffer overflow. Anyway to fix this?

CodePudding user response:

Replacing sizeof(myData) with std::size(myData) or with sizeof(myData) / sizeof(int) is fine, but IMO it would be better if you just use range-based for loop or/and use constant to define size of that array:

int main()
{
    static const DataSize = 10;
    int index, value;
    int count = 0;
    int myData [DataSize];
    for (auto &x : myData)
    {
        x = 1;
    }

    do
    {
        for (auto x : myData)
        {
            std::cout << x << " ";
        }

        std::cout << "Input index: ";
        std::cin >> index;
        std::cout << "Input value: ";
        std::cin >> value;

        myData[index] = value;

    } while (0 <= index && index < DataSize);

    std::cout << "Index out of range. Exit." << std::endl;
    
    return 0;
}

Disclaimer: your code is still invalid, but this is another issue.

CodePudding user response:

sizeof returns the number of bytes, not the number of ints. Consider

for (int i = 0; i < sizeof(myData) / sizeof(int); i  ) {
  std::cout << myData[i] << " ";
}

This will only work if the array is statically-sized like yours is. If the array is dynamically-allocated, as in new int[10], then C doesn't keep track of its size so that's your job. Of course, you should never be using new int[10] anyway, since std::vector is a thing and does keep track of size.

CodePudding user response:

As Silvio said, it stores number of bytes. You can also use a pointer as well

So your condition in for loop can look like

for (int i = 0; i < (sizeof(myData)/sizeof(*myData); i  )
  •  Tags:  
  • Related