#include <stdio.h>
int* two2one(int two_dimenstion[][2], int two_index, int one_dimenstion[5]);
#define INDEXTWO 3
#define INDEXT INDEXTWO+1
int main(void) {
int two_dimenstion[INDEXTWO][2] = { {4,-2} ,{1,4},{-3,1} };
int one_dimenstion[INDEXT];
int * result;
result = two2one(two_dimenstion, INDEXTWO, one_dimenstion);
for (size_t i = 0; i < INDEXT; i++)
{
printf("%d ", *(result + i));
}
return 0;
}
int* two2one(int two_dimenstion[][2], int two_index, int one_dimenstion[5]) {
int* p_one = one_dimenstion;
int index = 0;
for (size_t i = 0; i < (size_t)two_index; i++)
{
for (size_t j = 0; j < 2; j++)
{
int is_in = 0;
// 找出单一数字的作为数组的首元素
for (size_t n = i + 1; n < (size_t)two_index; n++)
{
if (two_dimenstion[i][j] == two_dimenstion[n][j])
{
is_in = 1;
}
else if (two_dimenstion[i][j] == two_dimenstion[n][1])
{
is_in = 1;
}
}
// 判断该元素是否为单一元素
if (is_in == 0)
{
p_one[index++] = two_dimenstion[i][j];
// 利用goto语句跳转
next_step:
// 判断该元素的数组下标是否为1
if (j > 0)
{
// 该元素前一个元素下标
size_t j1=0;
// 重新遍历二维数组
for (size_t n = 0, m = 0; n < (size_t)two_index; n++)
{
// 判断是否同该元素为同一位置,不是则进入
if (!(i == n && j1 == m))
{
// 寻找与之相等的值
for (size_t m = 0; m < 2; m++)
{
if (two_dimenstion[i][j1] == two_dimenstion[n][m])
{
// 赋值给一维数组
p_one[index++] = two_dimenstion[i][j1];
// 检查一维数组下标
if (index > (two_index + 1))
{
return p_one;
}
i = n;
j = m;
goto next_step;
}
}
}
}
p_one[two_index] = two_dimenstion[i][j1];
}
// 该元素的数组下标为0进入
else
{
// 该元素后一个元素下标
int j1 = 1;
// 注释同上
for (size_t n = 0, m = 0; n < (size_t)two_index; n++)
{
if (!(i == n && j1 == m))
{
for (size_t m = 0; m < 2; m++)
{
if (two_dimenstion[i][j1] == two_dimenstion[n][m])
{
p_one[index++] = two_dimenstion[i][j1];
if (index > (two_index + 1))
{
return p_one;
}
i = n;
j = m;
goto next_step;
}
}
}
}
// 当在二维数组遍历不到相同元素时,该元素就为一维数组的最后一个元素
p_one[two_index] = two_dimenstion[i][j1];
}
}
}
}
return p_one;
}
输出
-2 4 1 -3