[英]How to peek 2d array with Haskell inline-c
您好,我想使用2d arrays
:
--2d arrays
cArray :: IO (Ptr (Ptr CDouble))
cArray = do
x <- [C.block| double (*)[2] {
double (*ptd)[2] = malloc(sizeof(double[2][2]));
ptd[0][0] = 1.78;
ptd[0][1] = 1.68;
ptd[1][0] = 1.58;
ptd[1][1] = 1.48;
printf("the firstelement is: %f\n", ptd[1][1]);
return ptd;
}|]
return x
然后在另一个函数中:
e <- cArray :: IO (Ptr (Ptr CDouble))
e1 <- peekElemOff e 0 :: IO (Ptr CDouble)
e2 <- peekElemOff e1 0 :: IO CDouble
print e2
这总是会导致段错误。
对于一维数组,我没有问题。
谁能给我一个提示?
AC 2D 数组实际上只是一个 1D 数组,在其范围内,编译器会跟踪行长度以计算 2D 索引。 如果转换为Ptr (Ptr CDouble)
则此大小信息将丢失。 AC 2D 数组与数组数组 2D 数组不同——后者通常是锯齿状数组,但您也可以通过仅两次分配来更有效地获得这样的数组——一次用于内容,一次用于指向每个的指针排。
cArray :: IO (Ptr (Ptr CDouble))
cArray = [C.block| double** {
int n = 2, m = 2;
double* arr = malloc(sizeof(double[n*m]));
double** ptd = malloc(sizeof(double*[n]));
for (int i=0; i<2; ++i)
ptd[i] = &(arr[i*m]);
ptd[0][0] = 1.78;
ptd[0][1] = 1.68;
ptd[1][0] = 1.58;
ptd[1][1] = 1.48;
printf("the firstelement is: %f\n", ptd[0][0]);
return ptd;
}|]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.