Logic array in C - c

I am trying to test a logic function from four inputs a,b,c and d.
Each input is either 0 or 1.
I have been trying to accomplish this with arrays.
I want to pass back a 1 if a column in logicXY array matches that of the combLogic array.
int comb(int** combLogic, int** logicXY){
int x, y, logicOut;
for ( x = 0; x < 4; x++ ){
if (logicXY[0][x] == combLogic[x]){
logicOut = 1;
}
}
return logicOut;
}
int main void(){
int** combLogic[4] = {a,b,c,d}; /*logic input*/
int** logic[4][4] = {{1,0,0,1}, {1,0,1,1}, {0,1,0,0}, {0,1}}; /*return 1 if any of these combinations match the logic input*/
int comb(combLogic, logicXY); /*send to function*/
}
I know the function is not complete but I don't think I am passing the arrays correctly. I have read a number of tutorials but I cant seem to grasp the theory.
EDIT
I have got a few steps forward but it still isn't working. This is what I have now.
Function declaration in .h
int comb(logicInput,logicTest);
Function in .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;
}
The loop in part of the 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;
The code steps over the int comb(logicInput,LogicTest) and never carries out the function.
If I take out int from the line then it carries out the function, returns the value but when the value is written to output it is nothing like the value that was returned from the function.
EDIT
I have made a few changes to the code so it does appear to work and with only one warning from the compiler for the function declaration in .h that I cannot seem to fix.
warning: parameter names (without types) in function declaration [enabled by default]
Function declaration in .h
int comb(logicInput,logicTest);
Function in .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;
}
Loop in 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);
If I deviate from this code I just seem to end up with the compiler failing to build and even more warnings.

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;
in your loop:
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;
}

This is wrong:
int comb(int** logicInput, int** logicTest)
Try this:
int comb(int logicInput[4], int logicTest[4][4])
The difference is that int ** expects a pointer to a pointer (or an array of pointers), but when you define an array like you have then there are no pointers at all, so it doesn't work.
OK, technically, when you pass an array to a function it takes the address of that array and passes it by reference. This means you have a pointer to an array, but there are still no pointers inside that array.
When you pass an array you must always say what the dimensions of all but the first axes are, or else the compiler will not know how many entries to skip to get to the next row. In this case I gave the example as int [4][4], but it could just as well have been int [][4], should you have wished to give an unknown number of data rows.
The confusion arrises becuase C uses the same a[x] notation to access both int ** and int[n][m], but they do not look the same in memory.

Related

Use a function to change the contents of the array, i.e. multiply each number in the array by 2

Question
Use your function to change the contents of the array, i.e. multiply each number in the array by 2.
When your function has finished and your program continues in your main(), print the contents of your array in your main().
See if the changes made to the contents of the array in your function can be seen. If not, why?
Further
I'm trying to multiply the original array by 2 onto another array. Can anyone spot where I've went wrong?
#include <stdio.h>
#include <math.h>
#define SIZE 5
//function signatures
int getMultiples(int[]);
//main function
int main()
{
//main variables
int array[SIZE];
int multiples[SIZE];
printf("\nPlease enter 5 numbers into an array.\n");
for(int i = 0; i < SIZE; i++)
{
scanf("%d", &array[i]);
}
multiples[] = getMultiples(array);
printf("\nThis program will multiply all numbers by 2\n\n");
for (int i = 0; i < SIZE; i++)
{
printf("%d\n", multiples[i]);
}
return 0;
}
int getMultiples(int arr[])
{
//function variables
int i;
int multiples[SIZE];
for (i = 0; i < SIZE; i++)
{
multiples[i] = arr[i] * 2;
}
return multiples[];
}
This statement
multiples[] = getMultiples(array);
is syntactically and semantically invalid. This construction multiples[] is wrong and arrays do not have the assignment operator.
Also the definition of the function getMultiples is also wrong.
Again this statement
return multiples[];
is invalid.
What you are trying to do is to return the local array
int multiples[SIZE];
but the function return type is int. At least you needed to declare the return type as int *.
But in any case the local array that has automatic storage duration will not be alive after exiting the function.
If to use your approach then the function can look the following way
void getMultiples( int a1[], const int a2[], size_t n )
{
for ( size_t i = 0; i < n; i++ )
{
a1[i] = 2 * a2[i];
}
}
and in main the function is called like
getMultiples( multiples, array, SIZE );
Pay attention to that the function definition should not depend on the magic number SIZE.
By the way in your assignment there is written
Use your function to change the contents of the array, i.e. multiply
each number in the array by 2.
It means that you need to change the source array,
In this case the auxiliary array multiples is redundant. The function could be defined the following way
void getMultiples( int a[], size_t n )
{
for ( size_t i = 0; i < n; i++ )
{
a[i] *= 2;
}
}
and called in main like
getMultiples( array, SIZE );
You promise to return a single int.
int getMultiples(...);
You don't:
return multiples[];
You attempt to assign to a whole array (either a single int or an array....).
multiples[] = getMultiples(array);
That does not work in C.
And judging from what happens when trying your code, your compiler should have told you.

Understanding fractional knapsack, arrays and pointers

Just started learning C programming and decided to take a class in algorithmic Toolbox on Coursera. One of the challenges is writing a code using fractional knapsack, maximizing the value of loot and a pseudo code was given to help in coding the solution. Below are the pseudo code and the code I wrote for the pseudo code.
#include<stdio.h>
int min(int a, int b)
{
if (a < b)
return a;
else
return b;
}
int knapsack(int value[], int weight[])
{
int capacity = 100;
int val = 0;
int array[] = { 0 };
for (int i = 1; i < capacity; i++)
{
if (capacity == 0)
{
return val;
}
for (int i = 1; i < capacity; i++)
{
if (weight[i] > 0 && (value[i] / weight[i]))
{
int a = min(weight[i], capacity);
val = val + a * (value[i] / weight[i]);
weight[i] = weight[i] - a;
array[i] = array[i] + a;
capacity = capacity - a;
}
}
}
return val;
}
int main()
{
int value[100];
int weight[100];
scanf("%d", &value[100]);
scanf("%d", &weight[100]);
printf("%d", knapsack(value[100], weight[100]));
return 0;
}
pseudo code
Knapsack(W, w1,v1,......wn,vn)
A <-- [0,0,], V <-- 0;
repeat n times:
if W = 0:
return (V,A)
select i with Wi > 0 and max vi/wi
a <-- min(wi, W)
V <-- V + a(vi/wi)
wi <-- wi - a, A[i] <-- A[i] + a, W <-- W - a
return (V, A)
I am getting errors when I compile such as "passing argument 1 of 'knapsack' makes pointer from integer without a cast [-Wint-conversion]"
printf("%d", knapsack(value[100],weight[100]));
"expected int * but argument is of type 'int'"
int knapsack(int value[], int weight[])
I also want to know if it is a good practice to declare int value[], int weight[] in the function int knapsack argument and also more explanation in using arrays and pointers in situations like this.
int knapsack(int value[], int weight[])
The above statement gives the compiler the information about HOW the function should be called (type of arguments) and WHAT the function will return.
It says the function knapsack will return an integer value (the 1st int).
Its name is knapsack (case-sensitive).
It expects two arguments: an integer array (named value) and an integer array (named weight).
Points 1, 2 and 3 together make up the signature of a function.
To call the function you have to pass 2 integer arrays as its arguments.
The mistake : value[100] corresponds to an INTEGER ENTRY in the array and not the array itself.
To pass the array you should pass the array name as its argument, which your function expects.
Call the function like this: knapsack(value, weight)
value corresponds the array value and weight corresponds to the array weight
Also, passing value[100] corresponds to some garbage value that is not within the array bounds as you can only access elements ranging from value[0] to value[99] (0-based indexing).

How to use a 2d array in other function?? don't know how to make it work

me and my friend are trying to pass a user-defined array to a function and do a "2d array" sort mechanism on that array which is defined outside the function.
we found a function online that sorts a predefined array within itself and tried to use that function.
our problem consist in trying to use the user-defined array in the function.
please check the code below (please note that we don't know how to use structs)
The question is: how do we use our orderListArray[][] in the sort array function?
#include <stdio.h>
#include <stdlib.h>
// define for sort array function later on
#define ARRAYSIZE(array) (sizeof(array)/sizeof(*(array)))
// function prototype
int sortArray();
int printOrderlist();
// data variables to be used throughout the code.
int itemNumber;
int itemAmount;
int maxItem = 0;
int lineCount = 0;
int priceToPrint = 0;
float totalPrice = 0;
// array we wish to implement into "sortArray" function
int orderListArray[][2];
//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
int orderList()
{ // begin orderList
// makes sure user enters a maximum of 5 orders
int k = 0; // first place in array
int g = 0; // second place in array
do
{ // begin do1
printf("%d %d\n", k,g);
// asks for item number
puts("Enter item number (1-100):");
scanf("%d", &itemNumber);
// add scan to first spot (k) which is 0,0 (row 0, spot 0)
orderListArray[k][g] = itemNumber;
// add g++ to go to 0,1 ( row 0, spot 1)
g++;
// asks for amount
printf("%d %d\n", k, g);
printf("You can order %d more items\n", 5-itemAmount);
printf("Enter amount:\n");
scanf("%d", &itemAmount);
maxItem = maxItem + itemAmount;
// add itemAmount to g which is 0,1
orderListArray[k][g] = itemAmount;
k++; // go to row 1 instead of row 0
g--; // go back to spot 0 in row.
// lineCount is used when we print rows of array since that is not predefined
lineCount++;
} // end do1
// runs as long as the total amount of items inputed matches.
while (maxItem <= 4);
return 0;
} // end orderList
//////////////////////////////////////////////////////////////////////////////// //////////
//////////////////////////////////////////////////////////////////////////////// //////////
int main(void)
{
orderList();
sortArray();
return 0;
}
//////////////////////////////////////////////////////////////////////////////// //////////
//////////////////////////////////////////////////////////////////////////////// //////////
// is used in sortArray() to sort 2d array.
int compare(const void *a, const void *b) {
int x1 = *(const int*)a;
int x2 = *(const int*)b;
if (x1 > x2) return 1;
if (x1 < x2) return -1;
// x1 and x2 are equal; compare y's
int y1 = *(((const int*)a)+1);
int y2 = *(((const int*)b)+1);
if (y1 > y2) return 1;
if (y1 < y2) return -1;
return 0;
}
//////////////////////////////////////////////////////////////////////////////// //////////
//////////////////////////////////////////////////////////////////////////////// //////////
// sortArray function (here we want to implement the orderListArray[k][g]
// and run on that instead of predefined matrix which is included in the code
int sortArray(int b[], size_t size)
{ // begin sortArray
int matrix[][2] = {{8,6}, {4,2}, {1,0}, {4,8}, {2,4},
{4,3}, {1,2}, {2,2}, {8,3}, {5,5}};
printf("Original: ");
for (size_t i = 0; i < ARRAYSIZE(matrix); i++)
printf("(%d,%d) ", matrix[i][0], matrix[i][1]);
putchar('\n');
qsort(matrix, ARRAYSIZE(matrix), sizeof(*matrix), compare);
printf("Sorted : ");
for (size_t i = 0; i < ARRAYSIZE(matrix); i++)
printf("(%d,%d) ", matrix[i][0], matrix[i][1]);
putchar('\n');
return 0;
} // end sortArray
You have a bona fide 2D array. That's an array of arrays, so the elements are arrays, and therefore your compare function receives pointers to arrays as its arguments. Your comparison code is not actually wrong, but it would be a bit cleaner and clearer to acknowledge the correct types of the elements you are comparing:
int compare(const void *a, const void *b) {
const int (*x1)[2] = a;
const int (*x2)[2] = b;
if ((*x1)[0] > (*x2)[0]) return 1;
if ((*x1)[0] < (*x2)[0]) return -1;
if ((*x1)[1] > (*x2)[1]) return 1;
if ((*x1)[1] < (*x2)[1]) return -1;
return 0;
}
The main question seems to be represented by this code comment, however:
here we want to implement the orderListArray[k][g] and run on that instead of predefined matrix
It's not an especial problem for k to be an adjustable parameter, but it complicates matters greatly for g to be adjustable. To even declare your function requires either fudging types, or using a variable-length array. Either way, your function signature does not provide enough information. You must either know or assume both dimensions of your array, and you have only one parameter, size, to convey that information.
If you are assuming that the array to be sorted will be an array of pairs, as is matrix in your sample code, then simply write the function signature like so:
int sortArray(int b[][2], size_t size) // ...
and rely on the caller to provide the number of elements (pairs) via the size parameter. Then you could call qsort like so:
qsort(b, size, sizeof(*b), compare);
It's a lot messier if the matrix rows are variable length, because then you have to either dynamically choose a comparison function that is specific to the correct length, or generalize your comparison function and convey the row length to it by some means other than its arguments (thus, probably via a file-scope variable). Both of those approaches have significant drawbacks.
A third approach would be to rely on the caller of sortArray() to provide a suitable comparison function, but if you do that then you have to consider what value sortArray() is actually providing relative to calling qsort() directly.

Passing entire array to the function in C

I have written a program for insertion shot like following:
int _tmain(int argc, _TCHAR* argv[])
{
int arr[10] = {1,2,3,10,5,9,6,8,7,4};
int value;
cin >> value ;
int *ptr;
ptr = insertionshot(arr); //here Im passing whole array
BinarySearch(arr,value);
return 0;
}
int * insertionshot(int arr[])
{
//Changed after a hint (now, its fine)
int ar[10];
for(int i =0;i < 10; i++)
{
ar[i] = arr[i];
}
//Changed after a hint
int arrlength = sizeof(ar)/sizeof(ar[0]); //here array length is 1, it should be 10
for(int a = 1; a <= arrlength -1 ;a++)
{
int b = a;
while(b > 0 && ar[b] < ar[b-1])
{
int temp;
temp = ar[b-1];
ar[b-1] = ar[b];
ar[b] = temp;
b--;
}
}
return ar;
}
The problem is after passing the whole array to the function, my function definition only shows 1 element in array and also "arraylength" is giving 1.
int arr[] in a function formal parameter list is a syntax quirk, it is actually processed as int *arr. So the sizeof trick doesn't behave as you expect.
In C it is not possible to pass arrays by value; and furthermore, at runtime an array does not remember its length.
You could include the length information by passing a pointer to the whole array at compile time:
int * insertionshot(int (*arr)[10])
Of course, with this approach you can only ever pass an array of length 10. So if you intend to be able to pass arrays of differing length, you have to pass the length as another parameter.

what's the difference between int (* f [])(); and int f[]();

i find this in Pointers on C
int f[](); /* this one is illegal */
and:
int (* f [])(); /* this one legal. */
i really want know what's the usage of the second one.
thank you.
The second example is quite valid, if you use initialization block. For example:
#include <stdio.h>
int x = 0;
int a() { return x++ + 1; }
int b() { return x++ + 2; }
int c() { return x++ + 3; }
int main()
{
int (* abc[])() = {&a, &b, &c};
int i = 0,
l = sizeof(abc)/sizeof(abc[0]);
for (; i < l; i++) {
printf("Give me a %d for %d!\n", (*abc[i])(), i);
}
return 0;
}
I'm not sure if the second example is legal, since the size of the function array is not known, but what it is supposed to be is an array of function pointers, and here is a possible example of usage if the size would be known:
int a()
{
return 0;
}
int main(int argc ,char** argv)
{
int (* f [1])();
f[0] = a;
}
int f[](); // this is illegal because of you can't create array of functions . It's illegal in C
But second is legal
int (* f [])(); It says that f is an array of function pointers returning int and taking unspecified number of arguments
int f[](); /* this one is illegal */
That's trying to declare an array of functions, which is impossible.
int (* f [])(); /* this one NOT legal, despite what the OP's post says. */
That's trying to declare an array of function pointers, which would be perfectly legal (and sensible) if the array size were specified, e.g.:
int (* f [42])(); /* this one legal. */
EDIT: The type int (* f [])() can be used as a function parameter type, because for function parameter types, array-to-pointer conversion takes place immediately, meaning we don't ever need to specify the dimension of the innermost array of a (possibly multidimensional) array:
void some_func(int (* f [])()); /* This is also legal. */

Resources