因为没注意到'三目操作符'优先级比'+'低,漏了一个括号,造成内存越界,调试还看不出来,幸好有printf大法。
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
//#include<time.h>
void Initialize_bit(char *arr,int n);
void Clear_bit(char *arr,int n);
int Test_bit(char *arr,int n);
int main(){
//srand((unsigned int)time(0)*10000);
int number_max=0;
int count_prime_number=0;
//for(;number_max<9999;number_max=rand()%INT_MAX);
number_max=1000;
printf("number_max=%d\n",number_max);
int *numbers=(int *)calloc(number_max+1,sizeof(int));
char *numbers_tag=(char *)calloc((number_max+1)/CHAR_BIT+((number_max+1)%CHAR_BIT?1:0),sizeof(char));
for(int i=0;i<number_max+1;*(numbers+i)=i,i++);
Initialize_bit(numbers_tag,(number_max+1)/CHAR_BIT+((number_max+1)%CHAR_BIT?1:0));//记得加括号,因为'三目操作符'优先级比'+'低
Clear_bit(numbers_tag,0);
Clear_bit(numbers_tag,1);
for(int j=2,flag=0;1;j++,flag=0){
if(j!=2&&!(j%2))
j++;
for(int i=j*2;i<number_max+1;i+=j)
if(Test_bit(numbers_tag,i)){
Clear_bit(numbers_tag,i);
flag=1;
}
if(!flag)
break;
}
for(int i=1;i<number_max+1;count_prime_number+=Test_bit(numbers_tag,i)?1:0,i++);
printf("There were %d prime number between 0-%d:\n",count_prime_number,number_max);
for(int i=0,count=0;i<number_max+1;i++){
if(Test_bit(numbers_tag,i)){
count++;
printf("%d%c",*(numbers+i),count%10?32:10);
}
}
free(numbers);
numbers=NULL;
free(numbers_tag);
numbers_tag=NULL;
return 0;}
//
void Initialize_bit(char *arr,int n){
for(int i=0;i<n;*(arr+i)|=0xff,i++);
}
void Clear_bit(char *arr,int n){
*(arr+n/CHAR_BIT)&=~(1<<n%CHAR_BIT);
}
int Test_bit(char *arr,int n){
return *(arr+n/CHAR_BIT)>>n%CHAR_BIT&1;
}
|