2012-09-18 71 views
1

對不起,如果這很混亂....到目前爲止,我將十進制數轉換爲二進制數。在做這件事時,我將二進制表示的數字存儲到一個int數組中。C通過指針將多個int數組存儲到另一個數組中

EX:對於數字4(這在下面做DEC2BIN)

temp[0] = 1 
    temp[1] = 0 
    temp[2] = 0 

我想這個數組存儲到另一個陣列(比如BinaryArray)將包含多個「臨時」陣列。

我想BinaryArray聲明main,傳遞給dec2bin,並保存當前臨時數組的副本。然後轉到下一個號碼。

我很難搞清楚指針和什麼不需要這個。如果有人能夠幫助我如何在main中聲明所需的數組,以及如何從dec2bin中添加它。

謝謝! 主要:

#include <stdio.h> 
    #include <stdlib.h> 
    #include <string.h> 

    int main() 
    {  

     void dec2bin(int term, int size); 

     int size, mincount; 
     int * ptr; 
     int x; 
     x=0; 

     scanf("%d %d", &size, &mincount); 
     printf("Variables: %d\n", size); 
     printf("Count of minterms: %d\n", mincount); 

     int input[mincount+1]; 

     while(x < mincount){ 
     scanf("%d", &input[x]); 
     x++; 
     } 
     x = 0; 

     while(x < mincount){ 
     dec2bin(input[x], size); 

DEC2BIN:

#include <stdio.h> 
    #include <stdlib.h> 
    #include <string.h> 
    #define SIZE 32 

    void 
    dec2bin(int term,int size){ 
     int i, j, temp[size], remain, quotient; 
     quotient = term; 
     i = size-1; 
     // set all temp to 0 
     for(j=size-1;j>=0; j--){ 
     temp[j] = 0; 
     } 

     //change to binary 
     while(quotient != 0){ 
     remain = quotient % 2; 
     quotient/=2; 
     if(remain != 0){ 
      temp[i] = 1; 
     } else { 
      temp[i] = 0; 
     } 
     i--; 
     } 

     //print array 
     for(i=0; i<size; i++) 
      printf("%d", temp[i]); 

     printf("\n"); 
    } 
+0

嗨編輯請,主要貼兩次:)\ –

+0

當。剛離開房子。將不得不添加正確的東西在幾個 – Scape

+0

那麼,據我可以去現在沒有完整的代碼:爲什麼不聲明/存儲爲int **?直觀地說,就是一個int數組的數組。預先聲明尺寸可能不可能,如果你有不同大小的數字,導致mallocs,導致巨大的頭痛,因爲你做了一個陣列大小的假設,但... –

回答

4

不知道如果我明白你想要做什麼,但似乎你想創建一個「數組的數組」。 實施例:

#include <stdio.h> 
#include <stdlib.h> 

int main(){ 
    int i; 
    int n; 
    int **myArray; 

    n = 10; 
    myArray = (int**)malloc(n*sizeof(int*)); 

    //Usage example 
    int myIntArray[] = {1,2,3,4,5}; 

    myArray[0] = myIntArray; 

    //This call should print "4" 
    printf("%d\n",myArray[0][3]); 

    return; 
} 

這樣你將有一個陣列(myArray的),每個元素是整數的數組。

0

「所有溫度設定爲0」 時,使用的memset()。 我假設你想顯示一個二進制整數。您可以通過執行邏輯和0x80000000來檢查每個位,然後左移位變量。這裏是一個粗略的例子:

int x = 27; 
string bin; 

for (int index = 0; index < sizeof(int) * 8; ++index) { 
if (x & 0x80000000) { 
    bin += '1'; 
} else { 
    bin += '0'; 
} 
x = x << 1; 
} 
cout << bin << endl; 

爲什麼你想存儲一個整數的二進制表示在一個int數組中?我想不出有這個理由。

+0

嘗試比較kmaps。想想我會嘗試使用可變字母代替我在網上找到的東西 – Scape

相關問題