[英]How can I copy a struct member array to a variable?
I have the following basic C example:我有以下基本 C 示例:
#include <stdio.h>
struct Example {
double arr[4][4];
int size;
};
int main()
{
struct Example e = {
{{1., 0., 0., 0.},
{0., 1., 0., 0.},
{0., 0., 1., 0.},
{0., 0., 0., 1.}},
4
};
double** arr = e.arr;
printf("%8.5f %8.5f %8.5f %8.5f\n", arr[0][0], arr[0][1], arr[0][2], arr[0][3]);
printf("%8.5f %8.5f %8.5f %8.5f\n", arr[1][0], arr[1][1], arr[1][2], arr[1][3]);
printf("%8.5f %8.5f %8.5f %8.5f\n", arr[2][0], arr[2][1], arr[2][2], arr[2][3]);
printf("%8.5f %8.5f %8.5f %8.5f\n", arr[3][0], arr[3][1], arr[3][2], arr[3][3]);
}
What do I have to do to make the printf
successfully print out the values in the matrix?我该怎么做才能使printf
成功打印出矩阵中的值? If I declare arr
as double**
I get a segfault.如果我将arr
声明为double**
,则会出现段错误。 If I try double*
then it complains when I try to do double indexing.如果我尝试使用double*
,那么当我尝试进行双索引时它会抱怨。 I've also tried double arr[4][4] = e.arr
, but the compiler just tells me that it's an invalid initializer.我也尝试过double arr[4][4] = e.arr
,但编译器只是告诉我这是一个无效的初始化程序。 What's the proper way to do this?这样做的正确方法是什么?
(I realize size
is redundant in this example, I just wanted the struct to have more than one member.) (我意识到在这个例子中size
是多余的,我只是希望结构有多个成员。)
You can do like this since the values of double arr[4][4] are consecutive in memory您可以这样做,因为 double arr[4][4] 的值在 memory 中是连续的
double* arr = e.arr[0]; // points to first value
printf("%8.5f %8.5f %8.5f %8.5f\n", arr[0], arr[1], arr[2], arr[3]);
printf("%8.5f %8.5f %8.5f %8.5f\n", arr[4], arr[5], arr[6], arr[7]);
printf("%8.5f %8.5f %8.5f %8.5f\n", arr[8], arr[9], arr[10], arr[11]);
printf("%8.5f %8.5f %8.5f %8.5f\n", arr[12], arr[13], arr[14], arr[15]);
or alternatively, as @ismick pointed out in his comment you can write it like或者,正如@ismick 在他的评论中指出的那样,你可以这样写
double (*arr2)[4] = e.arr ;
printf("%8.5f %8.5f %8.5f %8.5f\n", arr2[0][0], arr2[0][1], arr2[0][2], arr2[0][3]);
printf("%8.5f %8.5f %8.5f %8.5f\n", arr2[1][0], arr2[1][1], arr2[1][2], arr2[1][3]);
printf("%8.5f %8.5f %8.5f %8.5f\n", arr2[2][0], arr2[2][1], arr2[2][2], arr2[2][3]);
printf("%8.5f %8.5f %8.5f %8.5f\n", arr2[3][0], arr2[3][1], arr2[3][2], arr2[3][3]);
if you want that syntax.如果你想要那种语法。
Alternative to the answer given by @AndersK, you can also try this.除了@AndersK 给出的答案,你也可以试试这个。
#include <stdio.h>
struct Example {
double arr[4][4];
int size;
};
int main()
{
int i, j;
struct Example e = {
{{1., 0., 0., 0.},
{0., 1., 0., 0.},
{0., 0., 1., 0.},
{0., 0., 0., 1.}},
4
};
double *arr = (double *)e.arr;
for(i = 0; i < 4; ++i)
{
for(j = 0; j < 4; ++j)
printf("%8.5f ", *(arr+i*4+j));
putchar('\n');
}
return 0;
}
In this we are pointing to the first block of memory where e.arr[0]
is stored, then we are traversing through the consecutive memory location using this expression (arr+i*4+j)
.在此,我们指向存储e.arr[0]
的 memory 的第一个块,然后使用此表达式(arr+i*4+j)
遍历连续的 memory 位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.