Wil Wil - 1 year ago 126
C++ Question

Changing int array to char array

Hello all I'm having difficulty running some code under various circumstances. I have code that finds how many prime numbers there are, of all the numbers in an array, times how long it takes, and prints how many prime numbers there are. This all works fine, but then I need to run the same code, but with a char array. That is where the problems come in. Here is the code, with an array of ints:

#include "stdafx.h"
#include <iostream>
#include <time.h>
#include <stdio.h>
using namespace std;

static const int N = 1000;

int main()
int i, a[N];

clock_t start = clock();

for (i = 2; i < N; i++) a[i] = i;
for (i = 2; i < N; i++)
if (a[i])
for (int j = i; j*i < N; j++) a[i*j] = 0;

start = clock() - start;

int primes = 0;
for (i = 2; i < N; i++) {
if (a[i]) {
cout << " " << i;
if (primes % 10 == 0)
cout << "\n";
printf("\nIt took %d clicks (%f seconds) to find all prime numbers.\n", start, ((float)start) / CLOCKS_PER_SEC);
cout << "The number of primes out of " << N << " integers is " << primes << endl;
return 0;

When I simply replace 'int' with "char" for the array, and set 'N' to something like 10, or 100 it works just fine, save for how the prime numbers look. Anything higher and nothing prints off. I know its not as simple as just changing where it says 'int' to 'char' but I am hopelessly lost on the subject. Doesnt help that I need to do this again, but changing the array to type bool (which doesnt make much sense to me either.)

Any kind of insight or simple solution would be wonderful. I will keep searching for something in the meantime. Thanks!

Answer Source

The problem is that you're storing i into a[i]. When a is a char array, the maximum value of an element is 127 (if char defaults to signed) or 255 (if it's unsigned), assuming a typical system with 8-bit bytes. If it's signed, overflow results in implementation-defined behavior; if it's unsigned, overflow wraps around modulo 256.

The only thing you care about is whether the value of the element is zero or non-zero, so there's no need to put different values in them. Just initialize them all to 1.

for (i = 2; i < N; i++) a[i] = 1;

This will also work when you change it to boolean.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download