I am making a program which stores prime numbers in a given range into an 1-d array dynamically. I have read about dynamic memory allocation in c,but i don't know what's wrong with my code. Initially I define an "isprime" function which checks whether a number is prime or not and if the number is prime it returns 1. After that I use a for loop which helps in storing of prime numbers in an array. In the for loop I use an if statement which checks whether the number in the range input by the user is prime or not,and if it is prime it is stored in an array p for which memory is allocated dynamically using malloc. But in the array p no prime numbers are stored and instead garbage values are stored,I don't know why prime numbers are not getting stored in my array?
#include<stdio.h>
#include<math.h>
int isprime(int n)
{
int i;
for(i=2;i<sqrt(n);i++)
{
if(n%i==0)
{
return 0;
}
}
return 1;
}
main()
{
int *p,i,n,j=1;
scanf("%d",&n);
for(i=0;i<n;i++)
{
if(isprime(i)&&i!=0&&i!=1)
{
p=malloc(j*sizeof(int));//Memory allocation for p should increase as more prime no.s are stored
p[j-1]=i;
j++;
}
}
printf("%d\n",p[1]);//garbage value is printed instead of any prime no.
}
malloc
will return a new memory region each time in your loop, losing your previous data.
You need realloc
instead
int *p = NULL; // initialize to NULL
and in the loop:
p=realloc(p,j*sizeof(int));
so either p
address is kept and memory increased, either previous data from p
is copied and a new p
is issued. Either way it's transparent for you.
(First time, as p
is NULL
, it acts like malloc
)
Note that it's rather inefficient to realloc
at each iteration. It would be better to resize less often, and keep record of capacity and actual data length. For instance like this:
Init:
int growth = 100;
int capacity = 0;
int *p = NULL;
and in the loop:
if (j>=capacity)
{
capacity += growth;
p = realloc(p,capacity*sizeof(int));
}
Aside: as comments noted, for the answer to full work, don't omit last value when checking for primes or you'll detect perfect squares as primes.