-3

I wonder why this program stopped working when I increase the value of array a[] If it has, plaese tell me how to increase this value without crashing Thanks

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{

    int i, j, save;
    char a[2082001];
    memset(a,'1',2082000);
    for (i=2;i<=2082000;i++)
    {
        if (a[i]=='1')
        {
            save=i;
            for (j=i*2;j<=2082000;j+=i)
                a[j]='0';
        }
    }
    printf("save = %d",save);
    return 0;
}
Phát Võ
  • 43
  • 3
  • 5
    It may be stack overflow. Try adding `static` before `char a[2082001]` and see if the program crashes to determine it is the cause or not. – MikeCAT Feb 26 '16 at 06:14
  • Let me guess, you're trying this on Windows, which only have a default 1MB default stack space per process? Now try to guess what happens when you try to create a 2MB array on the stack. – Some programmer dude Feb 26 '16 at 06:14
  • What do you mean with "Increase the value"? How do you do that? The current program works without problems... – arc_lupus Feb 26 '16 at 06:16
  • 1
    And after you fix the stack overflow problem, change `memset(a,'1',2082000);` to `memset(a, '1', 2082001);` or preferably, `memset(a, '1', sizeof a);` – Spikatrix Feb 26 '16 at 06:38
  • 'stopped working' - what? Error messages. please! – Martin James Feb 26 '16 at 07:35

1 Answers1

-2

Basic signed integer type. Capable of containing at least the [−32767, +32767] range; thus, it is at least 16 bits in size,

that takes j out of bounds.

Jonh Doe
  • 761
  • 1
  • 9
  • 25
  • 2
    It was very long time ago that `int` was only 16 bits. On any 32-bit system (and these days 64-bit systems) in production the last 30 years or so `int` is 32 bits. By the way, the range you show is wrong, it goes down to -32768. – Some programmer dude Feb 26 '16 at 06:18
  • 1
    @JoachimPileborg The range is not wrong. See N1256 5.2.4.2.1, which says that the least in absolute value of `INT_MIN` is `-32767` – MikeCAT Feb 26 '16 at 06:37
  • @MikeCAT On one's complement systems yes. Few of those around though, even fewer than 16-bit systems I would guess. :) – Some programmer dude Feb 26 '16 at 06:42