在 C 中获取子例程返回三个独立的随机数数组
我目前有一个子例程的代码,用于返回指向数组的指针。该数组是一维蒙特卡罗积分的随机数列表。我现在正在尝试做一个多维等效项,它需要 3 个随机数数组,而不是为每个数组都有一个单独的子例程,而是尝试创建一个返回 3 × N + 1 数组的子例程。有人可以帮我编码吗?一位伙伴提到我需要一个双指针,但到目前为止大多数网络资源都没有帮助。这是我的单个数组代码:
double* rdm_Y(void)
{
double* Random_number_list_Y = calloc(N + 1, sizeof(double));
int i;
sleep(1);
srand(time(NULL));
for (i = 1; i <= N; i++) {
Random_number_list_Y[i] = (float) rand() / (float) RAND_MAX;
}
return Random_number_list_Y;
}
非常感谢! 杰克·梅德利
I currently have code for a subroutine to return a pointer to an array. This array is a list of random numbers for a one dimensional monte-carlo integral. I am now trying to do a multi dimensional equivalent which requires 3 arrays of random numbers and instead of having a separate subroutine for each I'm trying to make one which returns a 3 by N + 1 array. Could somebody please help me with the coding for this. A mate mentioned I would need a double pointer but most web sources have been unhelpful thus far. Here is my single array code:
double* rdm_Y(void)
{
double* Random_number_list_Y = calloc(N + 1, sizeof(double));
int i;
sleep(1);
srand(time(NULL));
for (i = 1; i <= N; i++) {
Random_number_list_Y[i] = (float) rand() / (float) RAND_MAX;
}
return Random_number_list_Y;
}
Many Thanks!
Jack Medley
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
动态分配 T 类型的二维数组(其中 T 可以是
int
、double
等)的一般模式是The general pattern for dynamically allocating a 2D array of type T (where T can be
int
,double
, etc.) is尝试:
或者类似的东西
Try:
or something like this
我能想到的三种方法是:
*double
到一个大小为 3xN 的一维数组(你可以假装它是三个数组)**double
到一个数组三个*double
,每个都指向一个包含 N 的数组*double
,每个都指向一个包含 N 的数组如果您不喜欢假装方法 1,您可以再声明两个
*double
并将它们分别设置为返回值 + N 和 + 2N。另外,不要忘记free()
,您应该分别为每个方法执行 1、4 和 3 个free()
。The three methods I can think of are:
*double
to a 1D array of size 3xN (you can just pretend it's three arrays)**double
to an array of three*double
s, each one pointing to an array of Nstruct
containing three*double
s, each one pointing to an array of NIf you don't like pretending for method 1 you can declare two more
*double
s and set them to the return value + N and + 2N respectively. Also don't forget tofree()
you should have 1, 4, and 3free()
s to do for each of the methods respectively.