Okay so I tried the dynamically allocated array thing and it is working now, however another problem arises. I will post the entire code here for reference:
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cassert>
bool isPrime(char[], int, int);
void dealloc_arr(char[]);
char* extend_arr(char [], int, int);
int main()
{
int count = 1;
int y;
int length = 1;
char* array = newchar[length];
char* temp;
array[0] = 2;
for (y = 3; count < 10001 ; y+=2)
{
if (isPrime(array, length, y))
{
count+=1;
temp = extend_arr(array, length, y);
if (temp == NULL)//<== problem is here
{
printf("%d ", count);
fputs("could not extend the array\n", stderr);
exit (2);
}
else
{
array = temp;
}
length += 1;
}
}
printf("%d\n", y);
return EXIT_SUCCESS;
}
bool isPrime(char arr[], int size, int val)
{
char *ptr = arr;
for (int U = size; U > 0 ; U--)
{
if ((val / *ptr) < 3)
{
ptr++;
continue;
}
if (val % *ptr == 0)
returnfalse;
ptr++;
}
returntrue;
}
void dealloc_arr(char arr[])
{
delete[] arr;
arr = NULL;
}
char* extend_arr(char arr[], int length, int val)
{
char *array2 = newchar[length + 1];
int N = strlen(arr);
if (N == length)
{
for (int J = 0; J < length; J++)
array2[J] = arr[J];
array2[length] = val;
dealloc_arr(arr);
}
else
{
return NULL;
}
return array2;
}
My problem is that when I run this, at about the 25th prime it stops because the extend_arr is returning NULL. And this is because the length of the array sent to extend_arr is not matching up with 'length' variable.
@Cubbi, I was trying not to use dynamically allocated arrays, but I got a response above (@helios) that said I should try using that. I haven't used strings in such a while now, I don't know if I could go back to using them. I prefer char. This is just a project I am working on by myself, we are in break.
@firedraco, I don't know what you mean by "...don't ever null terminate your array..."
Couple things:
1. Let s[n] be the first element of s that is equal to 0. strlen(s) returns n, not the actual size of the array.
2. char typically overflows for values higher than 127. You'll want to use int or unsigned.
Since you're only initializing the first element of the array, because of my point #1 above, strlen() goes beyond the boundary of the array and returns a number that has nothing to do with the size of the array.
Remove the call to strlen() it does nothing for you because you already know the size of the array. You're passing it as a parameter. It's impossible for the array to be of a size different from that.