[英]Write Access Violation error in C while using rand()
我對使用 C 編程很陌生,所以希望有人能容忍我並幫助我解決我面臨的問題。
我正在編寫一個代碼來使用蒙特卡羅方法估計 pi 的值。 但是,當我構建和調試時,我收到一條錯誤消息:
“拋出異常:寫訪問沖突。a 是 0x1110112。
我在這行代碼中的 generate_random_array function 中收到此錯誤:
a[i] = (((double)rand() / (double)RAND_MAX) * 2.0 ) - 1.0;
我也發布了整個代碼以供參考。
注意:我正在使用帶有 MSVC 編譯器的 Visual Studio
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void generate_random_array(int sz, double a[]);
void count_points_inside_circle(int sz, double x[], double y[], int* counter);
int main()
{
int tot = 1000000000;
int incircle_c = 0;
double distance_sq, pi;
double* x = NULL;
double* y = NULL;
/*create arrays in the heap*/
x = malloc(tot * sizeof(double));
y = malloc(tot * sizeof(double));
/*generate random locations*/
generate_random_array(tot, x);
generate_random_array(tot, y);
/*count the points inside te circle by checking the location distance*/
count_points_inside_circle(tot, x, y, &incircle_c);
/*estimate pi*/
pi = 4.0 * incircle_c / (double)tot;
printf("pi estimated value using %d samples was found to be %lf", tot, pi);
free(x);
free(y);
return 0;
}
void generate_random_array(int sz, double a[]) {
int i;
srand(time(NULL));
for (i = 0; i < sz; i++)
a[i] = (((double)rand() / (double)RAND_MAX) * 2.0 ) - 1.0;
}
void count_points_inside_circle(int sz, double x[], double y[],int* counter_p) {
int i;
double distance_sq;
for (i = 0; i < sz; i++) {
distance_sq = x[i] * x[i] + y[i] * y[i];
if (distance_sq <= 1)
(*counter_p)++;
}
}
您必須始終對照NULL
檢查從malloc
返回的指針。 例如:
x = malloc(n * sizeof *x);
if (x == NULL) { /* Handle the failure and/or exit */ }
另一方面,此任務根本不需要使用數組(或用作數組的分配空間); 您只需要圓內的點數和生成的總點數。 可以這樣簡單地完成:
#include <stdio.h>
#include <stdlib.h>
double estimate_pi (unsigned trial_count)
{
const double rr = (double)RAND_MAX * RAND_MAX;
unsigned inner_point_count = 0;
unsigned i;
for (i = 0; i < trial_count; ++i) {
double x = rand();
double y = rand();
if (x * x + y * y <= rr)
++inner_point_count;
}
return 4.0 * inner_point_count / trial_count;
}
int main (void)
{
printf("%f\n", estimate_pi(1000000000));
return 0;
}
請注意,標准庫使用的隨機數生成器的質量會顯着影響此模擬的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.