One dimensional array being passed into the main() function - c

The below code works fine except for a one dimensional array I am trying to pass to main() from the function order_coef. I believe I am doing something wrong in the line where I specify *ordered_array=*array;, but not really sure what it is. Some help would be very much appreciated. Thank you!
#include <stdio.h>
#define COEF 5
int save_coef (int i, int *array);
int order_coef (int i, int *array, int *ordered_array);
int save_x (int x);
int resolve_polinomyal (int *array, int x, int i);
int main()
{
int array[COEF], x = 1, i = 0, *ordered_array=0;
printf("Please, enter 5 coefficients:\n");
save_coef (i, array);
order_coef (i, array, ordered_array);
for (i = 0; i < COEF; ++i)
printf("\n%d\n", ordered_array[i]);
printf("Please, enter the value of x:\n");
save_x (x);
printf("%d", resolve_polinomyal (array, x, i));
return 0;
}
int save_coef (int i, int *array)
{
for (i = 0; i < COEF; ++i)
{
scanf("%d", &array[i]);
}
return 0;
}
int order_coef (int i, int *array, int *ordered_array)
{
int j, a;
for (i = 0; i < COEF; ++i)
{
for (j = i + 1; j < COEF; ++j)
{
if (array[i] > array[j])
{
a = array[i];
array[i] = array[j];
array[j] = a;
}
}
}
*ordered_array=*array;
return 0;
}
int save_x (int x)
{
scanf("%d", &x);
return 0;
}
int resolve_polinomyal (int *array, int x, int i)
{
for (i = 5-1; i > 0; --i)
{
array[i-1] = array[i] * x + array[i-1];
}
return array[0];
}

The first problem is you do not allocate for ordered_array.
When you declare
int array[COEF], x = 1, i = 0, *ordered_array=0;
it means you initialized ordered_array = NULL.
You can use the static or dynamic allocation:
int ordered_array[COEF];
//
int *ordered_array = malloc(COEF*sizeof(int));
The second problem is *ordered_array=*array not copy array to array. It assigns first value of array to first value of ordered_array.
If you want to copy the value from an array to another one, you should use memcpy or a loop to copy value by value.
For example:
// copy the values of array to ordered_array
memcpy(ordered_array, array, COEF * sizeof(int));

Based on #Hitokiri comment I am pasting here the final solution with my code updated:
#include <stdio.h>
#define COEF 5
int save_coef (int i, int *array);
int order_coef (int i, int *array, int *ordered_array);
int save_x (int x);
int resolve_polinomyal (int *array, int x, int i);
int main()
{
int array[COEF], x = 1, i = 0, ordered_array[COEF];
printf("Please, enter 5 coefficients:\n");
save_coef (i, array);
order_coef (i, array, ordered_array);
for (i = 0; i < COEF; ++i)
printf("\n%d", ordered_array[i]);
printf("\nPlease, enter the value of x:\n");
save_x (x);
printf("%d", resolve_polinomyal (array, x, i));
return 0;
}
int save_coef (int i, int *array)
{
for (i = 0; i < COEF; ++i)
{
scanf("%d", &array[i]);
}
return 0;
}
int order_coef (int i, int *array, int *ordered_array)
{
int j, a;
for (i = 0; i < COEF; ++i)
{
for (j = i + 1; j < COEF; ++j)
{
if (array[i] > array[j])
{
a = array[i];
array[i] = array[j];
array[j] = a;
}
}
}
for (i = 0; i < COEF; ++i)
ordered_array[i] = array[i];
return 0;
}
int save_x (int x)
{
scanf("%d", &x);
return 0;
}
int resolve_polinomyal (int *array, int x, int i)
{
for (i = 5-1; i > 0; --i)
{
array[i-1] = array[i] * x + array[i-1];
}
return array[0];
}

Related

C programming - Sodoku solution (backtracking)

the Question is: to get from the user sodoku board and if there is a solution to print it, if not to print no solution!
the solution of the soduko: two identical numbers mmust not appear on the same line;
two identical numbers must not appear in the same colum.
I worte a program that works perfectly when I put the soduko board and the size (global parametes-as shown un my code) but when I tried to receive from the user it took so much time to run the solution and sometimes it didn't retun anything. I would like to understand why?!
#include <stdio.h>
#include <stdlib.h>
#define SIZE 5
int matrix[5][5] = {
{4,2,0,0,5},
{2,0,0,1,3},
{5,0,1,2,0},
{0,0,3,0,2},
{0,0,0,0,0},
};
void print_sudoku()
{
int i,j;
for(i=0;i<SIZE;i++)
{
for(j=0;j<SIZE;j++)
{
printf("%d ",matrix[i][j]);
}
printf("\n");
}
}
int number_unassigned(int *row, int *col)
{
int num_unassign = 0;
int i,j;
for(i=0;i<SIZE;i++)
{
for(j=0;j<SIZE;j++)
{
if(matrix[i][j] == 0)
{
*row = i;
*col = j;
num_unassign = 1;
return num_unassign;
}
}
}
return num_unassign;
}
int is_safe(int n, int r, int c)
{
int i;
for(i=0;i<SIZE;i++)
{
if(matrix[r][i] == n)
return 0;
}
for(i=0;i<SIZE;i++)
{
if(matrix[i][c] == n)
return 0;
}
return 1;
}
int solve_sudoku()
{
int row;
int col;
if(number_unassigned(&row, &col) == 0)
return 1;
int i;
for(i=1;i<=SIZE;i++)
{
if(is_safe(i, row, col))
{
matrix[row][col] = i;
if(solve_sudoku())
return 1;
matrix[row][col]=0;
}
}
return 0;
}
int main()
{
if (solve_sudoku())
print_sudoku();
else
printf("No solution!\n");
return 0;
}
and this is whe code that I used to ask the user to enter a sodoku board:
int** ReadSoduko(int n) {
int** matrix = (int**) malloc((sizeof(int*)) * n);
for(int i = 0; i < n; ++i) {
matrix[i] = malloc(sizeof(int) * n);
}
printf("\nEnter your soduko board:\n");
for(int i = 0; i < n; ++i) {
printf("Enter row [%d]: ", i);
for(int j = 0; j < n; ++j) {
scanf("%d", &matrix[i][j]);
}
}
return matrix;
}
I suspect your problem is related to one thing: #define SIZE that you are probably forgetting to update when reading dynamically. Since you use SIZE in your loops, if that is not the real size of your matrix, then it probably won't work. I've changed 2 lines and added 3 other (the lines with comments at the end). Try it now.
#include <stdio.h>
#include <stdlib.h>
int SIZE; //changed here
int** matrix; //changed here
void print_sudoku()
{
int i, j;
for (i = 0; i < SIZE; i++)
{
for (j = 0; j < SIZE; j++)
{
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
int number_unassigned(int* row, int* col)
{
int num_unassign = 0;
int i, j;
for (i = 0; i < SIZE; i++)
{
for (j = 0; j < SIZE; j++)
{
if (matrix[i][j] == 0)
{
*row = i;
*col = j;
num_unassign = 1;
return num_unassign;
}
}
}
return num_unassign;
}
int is_safe(int n, int r, int c)
{
int i;
for (i = 0; i < SIZE; i++)
{
if (matrix[r][i] == n)
return 0;
}
for (i = 0; i < SIZE; i++)
{
if (matrix[i][c] == n)
return 0;
}
return 1;
}
int solve_sudoku()
{
int row;
int col;
if (number_unassigned(&row, &col) == 0)
return 1;
int i;
for (i = 1; i <= SIZE; i++)
{
if (is_safe(i, row, col))
{
matrix[row][col] = i;
if (solve_sudoku())
return 1;
matrix[row][col] = 0;
}
}
return 0;
}
int** ReadSoduko(int n) {
int** matrix = (int**)malloc((sizeof(int*)) * n);
for (int i = 0; i < n; ++i) {
matrix[i] = (int*) malloc(sizeof(int) * n);
}
printf("\nEnter your soduko board:\n");
for (int i = 0; i < n; ++i) {
printf("Enter row [%d]: ", i);
for (int j = 0; j < n; ++j) {
scanf("%d", &matrix[i][j]);
}
}
return matrix;
}
int main()
{
printf("Size of matrix: "); //added this
scanf("%d", &SIZE); //added this
matrix = ReadSoduko(SIZE); //added this
if (solve_sudoku())
print_sudoku();
else
printf("No solution!\n");
return 0;
}
And don't forget that the matrix that you have declared statically doesn't have a solution! I have tested the same matrix, just replacing the 2 in first line by a 0 and it worked here.

How to sort an arrays of pointers, without changing the original array in C

Given two arrays: int nums[N] and int *ptrs[N] (N is a constant number).
I have to initialize the first array with some numbers. After that, i have to initialize the second array, so every element of the second array points to the element with the same index of the first array. (ptrs[0] points to nums[0],...).
Now i have to write a function with "ptrs" as argument that modifies the pointers in such a way that the first element of the second array points to the smallest number in the first array,..)
It's not allowed to change the "nums-array", i can only change the "ptrs-array".
This is my code i already have, but when i run it, the "nums-array" changes too.
What do i do wrong?
#include <stdio.h>
#define N 6
void sort(int *ptrs);
int main()
{
int nums[N] = { 1,6,7,8,2,5 };
int(*ptrs)[N];
int i;
ptrs = nums;
sort(ptrs);
for (i = 0; i < N; i++)
printf("nummer is: %d en %d\n", (*ptrs)[i], nums[i]);
return 0;
}
void sort(int *ptrs)
{
int i, j, tmp;
for (i = 0; i < N; i++)
for (j = i + 1; j < N; j++)
if ((ptrs)[i] > (ptrs)[j])
{
tmp = (ptrs)[i];
(ptrs)[i] = (ptrs)[j];
(ptrs)[j] = tmp;
}
}
Fix for the first part:
int main()
{
int nums[N] = { 1,6,7,8,2,5 };
int *ptrs[N]; // fix
int i;
for(i = 0; i < N; i++) // fix
ptr[i] = nums+i; // fix (or ptr[i] = &nums[i])
I found the solution, thanks for helping guys!
#include <stdio.h>
#define N 6
void sort(int ptrs[], int nums[]);
int main()
{
int nums[N] = { 1,6,7,8,2,5 };
int i,j,*p, *ptrs[N];
for (i = 0; i < N; i++) {
ptrs[i] = &nums[i];
}
sort(ptrs, nums);
return 0;
}
void sort(int *ptrs[], int nums[])
{
int i, j, tmp, p[N];
for (i = 0; i < N; i++)
p[i] = *ptrs[i];
for(j = 0; j < N; j++)
for (i = 0; i <= N; i++)
if (p[i] > p[i+1])
{
tmp = (ptrs)[i];
(ptrs)[i] = (ptrs)[i+1];
(ptrs)[i+1] = tmp;
for (i = 0; i < N; i++)
p[i] = *ptrs[i];
}
for (i = 0; i < N; i++)
printf("nummer is: %d en %d\n", *ptrs[i], nums[i]);
return;
}

How to write a comparator function for qsort for a 2D array?

I have an n*2 sized array. I want to sort them using qsort based on their value of the 2nd column.
#include<stdio.h>
int cmp(const int **a, const int **b) {
//return 0;
//return *a[1] - *b[1]
// return *a - *b;
}
int main()
{
int t; // test cases
scanf("%d", &t);
for(int i=0; i<t; i++) {
int n;
scanf("%d", &n); // size of array
int **arr = (int **)malloc(n * sizeof(int *));
for(int j =0; j< n; j++) {
arr[j] = (int *) malloc(2*sizeof(int));
}
for(int j =0; j< 2; j++) {
for(int k =0; k< n; k++) {
scanf("%d", &arr[k][j]);
}
}
for(int k =0; k< n; k++) {
for(int j =0; j<= 1; j++) {
printf("%d\t", arr[k][j]);
}
printf("\n");
}
// qsort(arr, n, sizeof(arr[0]), cmp);
}
return 0;
}
So for input,
1 2
3 6
0 8
5 4
8 9
5 7
Output is,
1 2
5 4
3 6
5 7
0 8
8 9
I tried but couldn't sort them according to their 2nd column. I am confused with passing array element to the comparator. Also with what to pass as the size of the element? But I guess that first 2 among below are correct.
qsort(arr, n, sizeof(arr[0]), cmp);
//qsort(arr, n, sizeof((int *)), cmp);
//qsort(arr, n, 2 * sizeof((int)), cmp);
I tried various combinations for the comparator.
Please hint out the way or perhaps an explanation.
The prototype for the comparison function is specified in the prototype for the qsort function:
void qsort(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *));
Your comparison function must be compatible, so you can define it this way:
int cmp(const void *a, const void *b) {
/* a and b are pointers to the array of pointers. */
int *aa = *(int * const *)a;
int *bb = *(int * const *)b;
return (aa[1] > bb[1]) - (aa[1] < bb[1]);
}
Or without casts:
int cmp(const void *a, const void *b) {
/* a and b are pointers to the array of pointers. */
int * const *aa = a;
int * const *bb = b;
int ia = (*aa)[1];
int ib = (*bb)[1];
return (ia > ib) - (ia < ib);
}
Note that you cannot use the simplistic comparison aa[1] - bb[1] as it can overflow for large values and at best produce incorrect output.
Furthermore, you input loop is incorrect: you should nest the loops in the opposite order:
for (int k = 0; k < n; k++) {
for (int j = 0; j < 2; j++) {
scanf("%d", &arr[k][j]);
}
}
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
int cmp(const void *a, const void *b) {
/* a and b are pointers to the array of pointers. */
int * const *aa = a;
int * const *bb = b;
int ia = (*aa)[1];
int ib = (*bb)[1];
return (ia > ib) - (ia < ib);
}
int main() {
int t; // test cases
scanf("%d", &t);
for (int i = 0; i < t; i++) {
int n;
scanf("%d", &n); // size of array
int **arr = malloc(sizeof(*arr) * n);
for (int j = 0; j < n; j++) {
arr[j] = malloc(sizeof(*arr[j]) * 2);
}
for (int k = 0; k < n; k++) {
for (int j = 0; j < 2; j++) {
scanf("%d", &arr[k][j]);
}
}
qsort(arr, n, sizeof(arr[0]), cmp);
for (int k = 0; k < n; k++) {
for(int j = 0; j < 2; j++) {
printf("%d\t", arr[k][j]);
}
printf("\n");
}
for (int j = 0; j < n; j++) {
free(arr[j]);
}
free(arr);
}
return 0;
}
You can also simplify the code using an actual 2D array:
#include <stdio.h>
#include <stdlib.h>
int cmp(const void *a, const void *b) {
const int *aa = a;
const int *bb = b;
return (aa[1] > bb[1]) - (aa[1] < bb[1]);
}
int main() {
int t; // test cases
scanf("%d", &t);
for (int i = 0; i < t; i++) {
int n;
scanf("%d", &n); // size of array
int (*arr)[2] = malloc(sizeof(*arr) * n);
for (int k = 0; k < n; k++) {
scanf("%d%d", &arr[k][0], &arr[k][1]);
}
qsort(arr, n, sizeof(arr[0]), cmp);
for (int k = 0; k < n; k++) {
printf("%d\t%d\n", arr[k][0], arr[k][1]);
}
free(arr);
}
return 0;
}
First of all you don't have a 2D array. You have a 1D array of pointers that each points to a 1D array of int.
So what you can do is to sort the 1D array of pointers. For that you can write a compare function that looks at the value of the pointed-to element.
It could look something like:
int cmp(const void * a, const void * b)
{
int* const * x = a;
int* const * y = b;
if ((*x)[1] < (*y)[1]) return -1;
if ((*x)[1] > (*y)[1]) return 1;
return 0;
}
As said above: It's the array of pointers that is sorted. You can visualize it like:

Array stores same number form a list of numbers twice

What my program does is that it takes an array of numbers that were read in from a file and sorts them with the selection sort and bubble sort methods. When it's sorted via the bubble sort method, the array lists one number twice in a row. It's also always the second number that gets copied. I checked to see if for whatever reason the number was actually getting passed to the new array twice, but it isn't. I also tried a different input file, same thing happens in the same place.This also cuts off the last number in the list. I don't see anything obvious in my code that's causing that to happen.
The list that the program calls is as follows:
10
50
78
83
92
100
0
4
72
3
19
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int findMin(int arr[], int start, int size);
void printArr(int arr[], int size);
void selectionSort(int arr[], int size);
void bubbleSort(int arr[], int size);
int main(int argc, char *argv[])
{
if(argc != 2)
{
printf("Syntax Error: ./<exec> <infile>\n");
exit(1);
}
FILE *ifp = NULL;
ifp = fopen(argv[1], "r");
if(ifp == NULL)
{
printf("Could not open %s for reading\n", argv[1]);
exit(1);
}
int counter;
int j = 0;
fscanf(ifp, "%d", &counter);
int array[counter];
int arrB[counter];
for(j = 0; j < counter; ++j)
{
fscanf(ifp, "%d", &array[j]);
}
for(j = 0; j < counter; j++)
{
arrB[j] = array[j];
}
int size = sizeof(array) / sizeof(int);
printf("Before: ");
printArr(array, size);
selectionSort(array, size);
bubbleSort(arrB, size);
fclose(ifp);
return 0;
}
int findMin(int arr[], int start, int size)
{
int i = 0;
int minLoc = start;
int minVal = arr[minLoc];
for ( i = start + 1; i < size; ++i)
{
if (arr[i] < minVal)
{
minVal = arr[i];
minLoc = i;
}
}
return minLoc;
}
void printArr(int arr[], int size)
{
int i = 0;
for(i = 0; i < size; ++i)
printf("%3d ", arr[i]);
printf("\n");
}
void selectionSort(int arr[], int size)
{
int i = 0;
int minLoc = 0;
int tmp = 0;
for(i = 0; i < size; ++i)
{
minLoc = findMin(arr, i, size);
tmp = arr[i];
arr[i] = arr[minLoc];
arr[minLoc] = tmp;
}
printf("** Selection Sort **\n After: ");
printArr(arr, size);
}
void bubbleSort(int arr[], int size)
{
int i = 0;
int j = 0;
int tmp = 0;
for(j = 0; j < size; j++)
{
for(i = 0; i < size; ++i)
{
if(arr[i] > arr[i+1])
{
tmp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = tmp;
}
}
}
printf("** Bubble Sort **\n After: ");
printArr(arr, size);
}
bubbleSort() accesses outside array bounds. Thus undefined behavior (UB).
for(j = 0; j < size; j++) {
for(i = 0; i < size; ++i) {
if(arr[i] > arr[i+1]) { // Here code access outside bounds when i = size - 1
... Code swaps arr[i], arr[i+1];
}
}
}
Instead
for(j = 0; j < size; j++) {
for(i = 1; i < size; ++i) {
if(arr[i-1] > arr[i]) {
... Code swaps arr[i-1], arr[i];
}
}
}

For loop won't stop

I've made an array that is between [0,1000], and I've printed it. Next step is to arrange the array using switch statements into five different cases 0 to 199, etc. When trying to do so the for loop won't stop. I tried putting a printf after countOne in case 1, no printout occurs either.
Any suggestions
Thanks for your help
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int n;
int arraySize;
int randN;
int rand();
int countOne = 0;
int countTwo = 0;
int countThree = 0;
int countFour = 0;
int countFive = 0;
int countSix = 0;
int *p;
int *p1;
int main()
{
printf("What is the size of the array\n");
scanf("%d", &n);
//MAKING THE N-size ARRAY
int array[n];
int i;
for (i = 0; i < n; i++) {
randN = rand() % 999;
array[i] = randN;
p = (int*)malloc(i * sizeof(int));
p[i] = array[i];
}
//SORTING THE N-size ARRAY
for (i = 0; i < n; i++) {
printf("%i\n", array[i]);
}
p = (int*)malloc(sizeof(int));
p1 = (int*)malloc(5 * sizeof(int));
p1[0] = countOne;
p1[1] = countTwo;
for (i = 0; i < n; i++) {
switch (i) {
case 1:
for (i = 0; array[i] >= 0 && array[i] <= 199; i++) {
countOne++;
}
case 2:
for (i = 0; array[i] >= 200 && array[i] <= 399; i++) {
countTwo++;
return countTwo;
}
}
}
}
HERE IS MY CODE AS OF CURRENT:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int n;
int arraySize;
int randN;
int rand();
int countOne = 0;
int countTwo = 0;
int countThree = 0;
int countFour = 0;
int countFive = 0;
int countSix = 0;
int *p;
int *p1;
printf("What is the size of the array\n");
scanf("%d", &n);
//MAKING THE N-size ARRAY
int array[n];
int i;
for (i = 0 ; i < n; i++ )
{
randN=rand() % 999;
array[i]=randN;
p=(int*)malloc(i*sizeof(int));
p[i]= array[i];
}
//PRINTING THE N-size ARRAY
for (i = 0; i < n; i++)
{
printf("%i\n", array[i]);
}
//SORTING THE N-size ARRAY
int j;
for (j = 0 ; j < n ; j++)
{
switch(j)
{
case 1:
for(i = 0 ; array[i] >= 0 && array[i] <= 199; i++)
{
countOne++;
return countOne;
}
case 2:
for(i = 0 ; array[i] >= 200 && array[i] <= 399; i++)
{
countTwo++;
return countTwo;
}
}
}
HERE IS THE PRINT OUT:
What is the size of the array
3
823
7
347
There is 0 integers between 0 and 199
There is 0 integers between 200 and 399
The program has many problems.
Here is a simpler version:
#include <stdio.h>
#include <stdlib.h>
int compare_ints(const void *a, const void *b) {
const int *pa = a, *pb = b;
return (*pa > *pb) - (*pa < *pb);
}
int main(void) {
int i, n;
int stats[5] = { 0, 0, 0, 0, 0 };
printf("What is the size of the array?\n");
scanf("%d", &n);
//MAKING THE N-size ARRAY
int *array = malloc(n * sizeof(int));
int *saved = malloc(n * sizeof(int));
if (array == NULL || saved == NULL) {
printf("cannot allocate arrays\n");
exit(1);
}
for (i = 0; i < n; i++) {
int randN = rand() % 999;
saved[i] = array[i] = randN;
stats[randN / 200] += 1;
}
printf("initial array contents:\n);
for (i = 0; i < n; i++) {
printf("%i\n", array[i]);
}
printf("\n");
//SORTING THE N-size ARRAY
qsort(array, n, sizeof(*array), compare_ints);
printf("sorted array:\n);
for (i = 0; i < n; i++) {
printf("%i\n", array[i]);
}
printf("\n");
for (i = 0; i < 5; i++) {
printf("%d values between %d and %d\n", stats[i], i * 200, (i + 1) * 200 - 1);
}
printf("\n");
// do whatever else you are supposed to with array and saved
//...
free(array);
free(saved);
return 0;
}

Resources