Prime numbers program

后端 未结 14 1494
无人及你
无人及你 2021-01-07 00:27

I\'m currently trying out some questions just to practice my programming skills. ( Not taking it in school or anything yet, self taught ) I came across this problem which re

14条回答
  •  隐瞒了意图╮
    2021-01-07 00:51

    I haven't looked at your code, but your array must be large enough to contain all the values you will store in it. 100 certainly isn't going to be enough for most input for this problem.

    E.g. this code..

    int someArray[100];
    someArray[150] = 10;
    

    Writes to a location large than the array (150 > 100). This is known as a memory overwrite. Depending on what happened to be at that memory location your program may crash immediately, later, or never at all.

    A good practice when using arrays is to assert in someway that the element you are writing to is within the bounds of the array. Or use an array-type class that performs this checking.

    For your problem the easiest approach would be to use the STL vector class. While you must add elements (vector::push_back()) you can later access elements using the array operator []. Vector will also give you the best iterative performance.

    Here's some sample code of adding the numbers 0-100 to a vector and then printing them. Note in the second loop we use the count of items stored in the vector.

    #include  // std::vector
    
    ...
    
    const int MAX_ITEMS = 100;
    
    std::vector intVector;
    
    intVector.reserve(MAX_ITEMS); // allocates all memory up-front
    
    // add items
    for (int i = 0; i < MAX_ITEMS; i++)
    {
      intVector.push_back(i);  // this is how you add a value to a vector;
    }
    
    // print them
    for (int i = 0; i < intVector.size(); i++)
    {
      int elem = intVector[i]; // this access the item at index 'i'
      printf("element %d is %d\n", i, elem);
    }
    

提交回复
热议问题