最初您的问题带有 C 标签。所以我会开始记住C。
数组没有赋值运算符。如果您想将一个数组的元素复制到另一个数组中,您应该使用在标头 <string.h> 中声明的标准函数 memcpy 或使用“手动”编写的循环。
这是一个演示程序
#include <stdio.h>
#include <string.h>
int main(void)
{
enum { M = 2, N = 4 };
int first[M][N] =
{
{ 7, 255, 0, 0 },
{ 6, 0, 255, 0 }
};
int second[M][N];
memcpy( second, first, M * N * sizeof( int ) );
for ( size_t i = 0; i < M; i++ )
{
for ( size_t j = 0; j < N; j++ )
{
printf( "%3d ", second[i][j] );
}
putchar( '\n' );
}
return 0;
}
程序输出是
7 255 0 0
6 0 255 0
另一方面,您可以将数组分配给指针。例如
int first[][4] = {{7, 255, 0, 0}, {6, 0, 255, 0}};
int ( *p )[4] = first;
或
int first[][4] = {{7, 255, 0, 0}, {6, 0, 255, 0}};
int ( *p )[sizeof( first ) / sizeof( *first )][4] = &first;
并使用指针访问数组中的元素。
另一种方法是将数组包装在结构中。在这种情况下,您将能够使用结构的赋值运算符将一个数组分配给另一个数组。
这是一个演示程序。
#include <stdio.h>
#include <string.h>
int main(void)
{
enum { M = 2, N = 4 };
struct Array
{
int a[M][N];
};
struct Array first =
{
{
{ 7, 255, 0, 0 },
{ 6, 0, 255, 0 }
}
};
struct Array second;
second = first;
for ( size_t i = 0; i < M; i++ )
{
for ( size_t j = 0; j < N; j++ )
{
printf( "%3d ", second.a[i][j] );
}
putchar( '\n' );
}
return 0;
}
它的输出和上图一样就是
7 255 0 0
6 0 255 0
如果您使用的是 C++,那么您可以使用标准容器,例如 std::array 或 std::vector,或者甚至将它们组合用于多维数组。
这是一个使用std::array的演示程序。
#include <iostream>
#include <iomanip>
#include <array>
int main()
{
std::array<std::array<int, 4>, 2> first =
{
{
{ { 7, 255, 0, 0 } },
{ { 6, 0, 255, 0 } }
}
};
std::array<std::array<int, 4>, 2> second;
second = first;
for ( const auto &row : second )
{
for ( const auto &item : row )
{
std::cout << std::setw( 3 ) << item << ' ';
}
std::cout << '\n';
}
return 0;
}
和往常一样,程序输出是
7 255 0 0
6 0 255 0