2016-05-31 45 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; 

}

相關問題