2013-07-11 39 views
3

我想從四個輸入a,b,c和d測試一個邏輯函數。在C中的邏輯陣列

每個輸入是0或1.

我一直在嘗試用數組來完成這個任務。

我想回傳一個1,如果logicXY數組中的一列與combLogic數組的列相匹配。我知道函數不完整,但我不認爲我正確地傳遞數組。我讀了一些教程,但我似乎無法理解這個理論。

編輯 我已經有了幾步,但它仍然無法正常工作。這是我現在擁有的。在.H

int comb(logicInput,logicTest); 

功能

函數聲明以.c

/* Function - Combination */ 
int comb(int** logicInput, int** logicTest){ 
int x, y, logicOut; 
    for (x = 0; x < 4; x++){ 
     if (logicTest[0][x] == logicInput[x]){ 
       logicOut = 1; 
       } 
    } 
    return logicOut; 
} 

環路在main.c中的一部分

int output = 0; 
int logicInput[4] = {0,1,1,1}; 
int logicTest[4][4] = {{1,0,0,1}, {1,0,1,1}, {0,1,0,0}, {0,1,1,1}}; 
int comb(logicInput,logicTest); 
output = comb; 

int comb(logicInput,LogicTest)的代碼步驟和從不執行功能。 如果我從行中取出int然後它執行該函數,返回該值,但是當該值寫入輸出時,它與從該函數返回的值不同。

編輯

所以它似乎工作,從編譯器中的.h函數聲明,我似乎無法修復只有一個警告,我已經對代碼進行一些更改。在.H

int comb(logicInput,logicTest); 

功能

warning: parameter names (without types) in function declaration [enabled by default] 

函數聲明以.c

int comb(int** logicInput, int** logicTest){ /*Points to the arrarys in the main program*/ 
int x, i, logicOut; 
    for(i = 0; i < 4; i++){ /*test each column*/ 
    for (x = 0; x < 4; x++){ /*test each row*/ 
     if (logicTest[i][x] == logicInput[i][x]){ 
      logicOut = 1; 
      break; 
      } 
} 
    if(logicOut == 1)break; /*Break when logicOut == 1 the first time it happens*/ 
} 
return logicOut; 
} 

循環main.c中

int output; 
int logicInputC1[4] = {0,1,0,1}; 
int logicTestC1[4][4] = {{1,0,0,1}, {1,0,1,1}, {0,1,0,0}, {0,1,0,1}}; 
output = comb(logicInputC1,logicTestC1); 

如果我從這個代碼偏離我只是似乎最終導致編譯器無法構建甚至更多的警告。

+0

實際上問題是'combLogic'和'logic'的聲明,你可以檢查這個代碼[如何聲明/傳遞'int' 2D-martix?](http://stackoverflow.com/questions/17566661/ c-dynamic-array-initalization-with-declaration/17567663#17567663) –

+0

函數如何知道尺寸(尤其是combLogic)? –

+1

問題出在'main()'中的數組聲明中,也出現在參數列表中。請注意,'int ** param'和'int param [] [4]'是不同的類型。您的編譯器應該抱怨在數組中使用'1'作爲初始值設定項。它也應該抱怨調用'comb()'的類型不匹配。 –

回答

3
int * comblogic[4] = {a, b, c, d} //where a, b, c, and d, are arrays of size 4; aka int  a[4]; 
int logicArray[4][4] = values; 
在循環

int comb(int** combLogic, int** logicXY){ 
    int x, y, logicOut; 
    for(int i = 0; i < 4; i++){ 
    for (x = 0; x < 4; x++){ 
     if (logicXY[i][x] == combLogic[i][x]){ 
      logicOut = 1; 
      break; 
      } 
} 
    if(logicOut == 1)break; //incase you want to break when logicOut == 1 the first time it happens 
} 
return logicOut; 
} 
+0

什麼是'logicArray'和'values'?爲什麼要創建一個指向數組的指針數組?只是爲了能夠寫'int ** logicXY'?阿姆斯的答案要好得多。 –

2

這是錯誤的:

int comb(int** logicInput, int** logicTest) 

試試這個:

int comb(int logicInput[4], int logicTest[4][4]) 

不同的是,int **需要一個指針的指針(或者arr指針),但是當你像你一樣定義一個數組時,根本就沒有指針,所以它不起作用。

好的,從技術上講,當你傳遞一個數組到一個函數時,它需要該數組的地址並通過引用傳遞它。這意味着你有一個指向數組的指針,但該數組內仍然沒有指針。

當你傳遞一個數組時,你必須說出除第一個軸以外的所有維的大小,否則編譯器將不知道有多少條要跳到下一行。在這種情況下,我舉例爲int [4][4],但如果您希望給出未知數量的數據行,它也可能是int [][4]

由於混淆原因C使用相同的a[x]表示法訪問int **int[n][m],但它們在內存中看起來不一樣。

+0

+1。更好的答案。 –