I'm trying to implement a function that receives an array of integers and its capacity and fills the array with all the values read from the keyboard which are prime numbers, without overflowing it, and returns the number of elements copied into the array. It fills the values properly but doesn't stop when there are no more prime numbers to be copied and just fills the remaining positions with garbage values. Why is that?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <string.h>
#define MAX 101
unsigned checkNumber(char *word)
{
int i, len = strlen(word);
for(i = 0; i < len; i++)
{
if(!isdigit(word[i]))
return 0;
}
return 1;
}
unsigned isPrime(int n)
{
int i, m = n/2;
for(i = 2; i <= m; i++)
{
if(n%i == 0)
{
return 0;
break;
}
}
return 1;
}
void countPrimes(char *s, int *arr, size_t cap)
{
int n, countPrimes = 0;
while(fgets(s, MAX, stdin))
{
s[strlen(s)-1] = '\0';
char *word = strtok(s, " ");
while(word)
{
if(checkNumber(word))
{
n = atoi(word);
//printf("Word : %s\n", word);
if(isPrime(n))
{
if(countPrimes < cap)
{
arr[countPrimes] = n;
countPrimes++;
cap -= countPrimes;
}
//countPrimes++;
//cap -= countPrimes;
//printf("Prime number : %d\n", n);
}
//break;
}
word = strtok(NULL, " ");
}
//printf("There are %d prime numbers on this line.\n", countPrimes);
}
}
int main()
{
char s[MAX];
int arr[10];
countPrimes(s, arr, sizeof(arr)/sizeof(arr[0]));
for(int i = 0; i < sizeof(arr)/(sizeof(arr[0])); i++)
{
printf("%d\n", arr[i]);
}
return 0;
}
Input:
13 abcd 2 4 8 10 abc3 17 31
Output:
13
2
17
31
0
0
0
0
0
0
If it was an array of characters after if(countPrimes < cap) I would just write arr[countPrimes] = '\0', but being an array of integers how can I signal that the copying stops?