简体   繁体   English

在C中将一维数组复制到二维数组

[英]Copy one dimensional array to two dimensional array in C

I have a code something like this, but I want to display it in two dimensional array like 4*10. 我有一个类似这样的代码,但是我想以二维数组(如4 * 10)显示它。 I'm thinking of copying the elements of one dimensional array to two dimensional. 我正在考虑将一维数组的元素复制到二维。 But how can i edit this below code. 但是我如何编辑下面的代码。 Thank you. 谢谢。

long int arr[40];

printf("The Fibonacci range is: ");

arr[0]=0;
arr[1]=1;

for(i=2;i<range;i++){
     arr[i] = arr[i-1] + arr[i-2];
}

  for(i=0;i<range;i++)
     printf("%ld ",arr[i]);

You have all of the one dimensional completed. 一维都已经完成。 Using the same process you can add it to array[x][y] , and loop through. 使用相同的过程,可以将其添加到array [x] [y]并循环遍历。 The only thing is you would need to keep track of two indexes instead of one. 唯一的事情是您需要跟踪两个索引而不是一个。 Code it all and you will get it. 全部编码,您将得到它。

If its only for display reasons you don't have to copy the array just fix it in the print: 如果仅出于显示原因而不必复制阵列,只需在打印中将其修复:

for(i=0;i<range;i++) {
   if (i%10 == 0)
       printf("\n");
   printf("%ld ",arr[i]);
}

Thats will print the array in 4 diff lines as I guess you wanted. 如我所愿,那将以4个差异行打印数组。

Hope that's help 希望有帮助

check out this 看看这个

#include <stdio.h>

int main(void) {

long int arr[40];
long int twoD[4][10];
int i,range,j,k;
printf("The Fibonacci range is:\n ");
scanf("%d",&range);  // getting range value from user

arr[0]=0;
arr[1]=1;

for(i=2;i<range;i++){
     arr[i] = arr[i-1] + arr[i-2];
}

 i=0; // reinitialize i to 0.
     for(j=0;j<4;j++){
        for(k=0;k<10;k++){
            twoD[j][k]=arr[i++];  // coping 1D to 2D array
        }
     }

     for(j=0;j<4;j++){
        for(k=0;k<10;k++){
        printf("%ld ",twoD[j][k]); // printing 2D array
        }
        printf("\n");
     }

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM