#include<stdio.h>
#define ARSIZE 1000000
int main()
{
    int i=0,j=0,c=0,k,n;
    int prep[ARSIZE];
    for(i=0;i<1000000;i++)
    {
                          j++;
                          for(k=2;k<j;k++)
                          {
                                          if(j%k==0)
                                          c++;
                                          }
                                          if(c==2)
                                          prep[i]=j;
                                          c=0;
                                          }
                                          printf("Enter N : ");
                                          scanf("%d\n",&n);
                                          printf("%d",prep[n-1]);
                                          getch();
                                          return 0;
                                          }

why is this code giving segmentation fault??

You have probably corrupted your stack by using an array with automatic storage duration that is too large. Try reducing the array size and run the code again.

#define ARSIZE 1000000

You have probably corrupted your stack by using an array with automatic storage duration that is too large. Try reducing the array size and run the code again.

#define ARSIZE 1000000

thanks a lot. It worked. But does that mean there is an upper limit to the number of elements I can store in an array?? In that case, how is the limit decided?

You need to understand the computer program memory layout in C. In C or C++ local objects are usually allocated on the stack. You are allocating something large on the stack, more than the stack can handle, so you are getting a STACKOVERFLOW.

If you allocate the array on the heap you should be fine, assuming your machine has enough memory.

int* array = new int[1000000];

But remember that this will require you to delete[] the array.

Another way to achive it making the variable global.This will allocate in the HEAP.

Check out below link for C memory layout:
http://book.chinaunix.net/special/ebook/addisonWesley/APUE2/0201433079/ch07lev1sec6.html

You've provided an excellent answer, vikashj, except that new and delete are not going to work in C.

Oh.. sorry, you can use malloc and free instead.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.