2016-05-31 82 views
-3

当涉及到C语言并插入到数组中时,我完全卡住了。我有我的代码在下面,并解释说,用户想要一个数组3.所以用户输入4 3 2到数组a1[n]。我需要数组a2[]输出相同的数字,但每个之间为零。当输出a2[]时,最终结果将为4 0 3 0 2 0。我将如何在每个其他元素之间得到一个零?在我的数组中的每个元素之间插入一个数字C

#include <stdio.h> 

    int main() { 

    int n = 0; 
    int number = 0; 
    int a1[n]; 
    int a2[2 * n]; 

    printf("Enter the length of the array: "); 
    scanf("%d", &n); 

    printf("Enter the elements of the array: "); 

    for(i = 0; i < n; i++){ //adds values to first array 
      scanf("%d",&number); 
      a1[i] = number; } 

    for(i = 0; i < n; i++){ //copies and sets the arrays the same 
      a2[i] = a1[i]; } 
+0

是否一定有一个与那些零数组?您可以在输出数组时直接插入它们。 – LibertyPaul

+0

不,这不是必要的,但会帮助我学习任何一种方式 – user6124417

回答

2

假设你的阵列被正确定义和初始化(静态或动态),它仅仅是一个PR的事在复制过程中进行正确计数:

for(int i = 0; i < n; i++){ 
     a2[i+i] = a1[i]; 
     if(i < n-1) a2[i+i+1] = 0; 
     } 
+0

非常感谢你这是我需要的for循环!稍微复杂一些,我会想到自己。 – user6124417

-1

你必须乘以2的指数:

for(i = 0; i < n; ++i) { //copies and sets the arrays the same 
    a2[2 * i] = a1[i]; 
} 

不仅如此,中a2奇数索引的元素应设置为零。您可以在回路明确做到这一点:

for(i = 0; i < n; ++i) a2[2 * i + 1] = 0; 

但是简单是先用零初始化数组:

int a2[2 * n] = {0}; 

偶数元素将在以后与a1元素覆盖。

0
int n = 0; 
int number = 0; 
int a1[n]; 
int a2[2 * n]; 

恭喜,现在a1a2是零长度的阵列。即使您以后更改了n,这也不会影响阵列的长度。在C中,你不能使数组长或短。

尝试使用int*calloc

0

首先,您不能使用运行时定义的大小创建stack-allocatedstatic数组。

int a[N]; // N should be determined during compilation 

您应该使用heap-alloceteddynamic阵列:

int *a; 
a = (int *)malloc(2 * n, sizeof(int)); // n may be defined by user input 

有没有办法来调整阵列,而不将其移动到另一个地方,你可以创建一个新的(更大然后第一)和与源号码和零填充:

#include <stdio.h> 

int main() { 
    int n = 0; 
    printf("Enter the length of the array: "); 
    scanf("%d", &n); 

    int *a1 = (int *)malloc(n, sizeof(int)); 
    int *a2 = (int *)malloc(n * 2, sizeof(int)); 

    printf("Enter the elements of the array: "); 

    int i, number; 
    for(i = 0; i < n; i++){ //adds values to first array 
     scanf("%d",&number); 
     a1[i] = number; 
    } 

    for(i = 0; i < n; i++){ //copies and sets the arrays the same 
     a2[i * 2] = a1[i]; 
     a2[i * 2 + 1] = 0; 
    } 

    for(i = 0; i < n * 2; ++i){ 
     printf("%d ", a2[i]); 
    } 
} 
+0

[可变长度数组](https://en.wikipedia.org/wiki/Variable-length_array)确实允许您使用运行时定义的方式创建堆栈分配数组尺寸。 – user3386109

+0

“你不能创建堆栈分配...与运行自定义大小” - >你说的代码不能使用'的scanf( “%d”,&n); INT A1 [N];'(VLA在C99) – chux

+0

那些'malloc'应该释放 – 3kt

0

在上一个循环中添加以下代码。

为(J = 0,I = 0;我< = N; i ++在){

a2[j++] = a1[i]; 
a2[j++] = 0; 

}

相关问题