C: Why doesn't this code work? - c

Need help with this code it should return c[] with the number's of a[] % b[] = 0 but it doesn't work.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int *divide(int a[], int a_size, int b[], int b_size)
{
int i = 0, j = 0, k = 0, counter = 0, *c;
c = (int*)malloc(b_size * sizeof(int));
for (i = 0; i < b_size; i++)
{
for (j = 0; j < a_size; j++)
{
if (a[j] % b[i] == 0)
counter++;
}
c[k] = counter;
k++;
counter = 0;
}
for (int t = 0; t < b_size; t++)
{
printf("%d ", c[t]);
}
printf("\n");
}
main ()
{
int *a, *b, a_size, b_size;
printf("Enter size of a:\n");
scanf ("%d", &a_size);
a = (int*)malloc(a_size * sizeof(int));
printf("\nEnter size of b:\n");
scanf("%d", &b_size);
b = (int*)malloc(b_size * sizeof(int));
printf("\nEnter elements of a:\n");
for (int i = 0; i < a_size; i++)
{
scanf("%d", &a[i]);
}
printf("\nEnter elements of b:\n");
for (int j = 0; j < b_size; j++)
{
scanf("%d", &b[j]);
}
divide(&a, a_size, &b, b_size);
}

There was some errors in your code.
You want your fonction *divide(...) to return a new array containing the operation a[i] % b[i], but your function doesn't return anything, so you have to return it. It seems more logical to print the new array in the main, than in the function while doing it.
When you pass the variables to your function be careful to pass int*, not int **.
Here is a sample of code which works (you didn't say what to do if a_size and b_size were different so I assume we only use the smallest size and don't treat the number after) :
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int *divide(int a[], int a_size, int b[], int b_size)
{
int i = 0, stop, *c;
if (b_size <= a_size)
{
c = (int*)malloc(b_size * sizeof(int));
stop = b_size;
}
else
{
c = (int*)malloc(a_size * sizeof(int));
stop = a_size;
}
while (i < stop)
{
c[i] = a[i] % b[i];
i++;
}
return (c);
}
int main ()
{
int *a, *b, a_size, b_size;
int *result = NULL;
int stop;
int i = 0;
printf("Enter size of a:\n");
scanf ("%d", &a_size);
a = (int*)malloc(a_size * sizeof(int));
printf("\nEnter size of b:\n");
scanf("%d", &b_size);
b = (int*)malloc(b_size * sizeof(int));
printf("\nEnter elements of a:\n");
for (int i = 0; i < a_size; i++)
{
scanf("%d", &a[i]);
}
printf("\nEnter elements of b:\n");
for (int j = 0; j < b_size; j++)
{
scanf("%d", &b[j]);
}
result = divide(a, a_size, b, b_size); //not &a neither &b because it would be a char** instead of a char*
if (a_size < b_size)
stop = a_size;
else
stop = b_size;
while (i < stop)
{
printf("%d ", result[i]);
i++;
}
return 0;
}

Related

I'm not able to read my matrix dynamically

My program crashes when it comes to the reading function, at the scanf line. What can I do?
I'm guessing it's an issue with the way I wrote (*(a + i) + j) but I can't tell.
void read(int **a, int n)
{
int i, j;
for(i=0;i<n;i++)
for (j = 0; j < n; j++)
{
printf("a[%d][%d]=", i, j);
scanf("%d", (*(a + i) + j)); //Access violation writing location
}
}
void show(int**a, int n)
{
int i, j;
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
{
printf("%d", *(*(a + i) + j));
}
}
int main()
{
int n,opt,a;
printf("number of lines and columns:");
scanf("%d", &n);
a = (int**)malloc(n*n * sizeof(int));
while (1)
{...
A dynamic 2D n x n array is allocated using this code:
int (*a)[n] = malloc(n * sizeof *a);
It means: Declare a as pointer to an integer array with n element and allocate n of those arrays (i.e. n * sizeof *a). In that way it ends up with n x n integers.
So a full version of your code could be like:
#include <stdio.h>
#include <stdlib.h>
void read(int n, int a[][n])
{
int i, j;
for(i=0;i<n;i++)
for (j = 0; j < n; j++)
{
printf("a[%d][%d]=\n", i, j);
scanf("%d", &a[i][j]);
}
}
void show(int n, int a[][n])
{
int i, j;
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
printf("%d ", a[i][j]);
}
puts("");
}
}
int main(void)
{
int n = 0;
printf("number of lines and columns:\n");
scanf("%d", &n);
if (n < 1) exit(1);
int (*a)[n] = malloc(n * sizeof *a);
read(n, a);
show(n, a);
free(a);
return 0;
}
note : To keep it simple I skipped all check of scanf return values. In real code, the scanf return value shall always be checked.
There is nothing wrong with allocating a block using malloc ( n * n * sizeof *a);
The address of the block must be assigned to a pointer int *a
Elements can be accessed by (a + i * n + j) or a[i * n +j]
void read(int *a, int n)
{
int i, j;
for(i=0;i<n;i++)
for (j = 0; j < n; j++)
{
printf("a[%d][%d]=", i, j);
scanf("%d", (a + i * n + j));
// scanf("%d", &a[i * n + j]);
}
}
void show(int *a, int n)
{
int i, j;
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
{
printf("%d", *(a + i * n + j));
// printf("%d", a[i * n + j]);
}
}
int main()
{
int n = 0, opt = 0, *a = NULL;
printf("number of lines and columns:");
scanf("%d", &n);
a = malloc ( n * n * sizeof *a);
while (1)
{...

How can I move all elements in an array with a K number and make the numbers rotate when it comes to the end?

#include <stdio.h>
#include <stdlib.h>
int main()
{
int N, K, i;
printf("Enter size of array: ");
scanf("%d", &N);
printf("Please enter value of K: ");
scanf("%d", &K);
int arr[N];
for (i = 0; i < N; i++)
{
scanf("%d", &arr[i]);
}
for (i = 0; i < N; i++)
{
int temp = arr[i];
arr[i + K] = arr[i];
arr[i] = temp;
}
for (i = 0; i < N; i++)
{
printf("%d", arr[i]);
}
return 0;
}
I know the current code is totally wrong It was just another test.
Basically what I need to do is something like this:
the array before: arr[N]={1,2,3,4,5,6,7,8,9,10}
the array after if K is 2: arr[N]={10,9,1,2,3,4,5,6,7,8}
Like #whozcraig pointed out for in-place rotation of array members.
Define a function to reverse(in-place) array members in a range :
static inline void
arr_reverse (const int start, const int end, int arr[]) {
for (int ai = start, zi = end; ai < zi; ++ai, --zi) {
int tmp = arr[ai];
arr[ai] = arr[zi];
arr[zi] = tmp;
}
}
Then you call it like :
K %= N;
if (K != 0) {
arr_reverse (0, N-1, arr);
arr_reverse (0, K-1, arr);
arr_reverse (K, N-1, arr);
}
I write something like this but it creates new array instead of modifying current one but it works.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int N, K, i;
printf("Enter size of array: ");
scanf("%d", &N);
printf("Please enter value of K: ");
scanf("%d", &K);
int arr[N], newArr[N];
for (i = 0; i < N; i++)
{
scanf("%d", &arr[i]);
}
for (i = 0; i < K; i++)
{
newArr[i] = arr[N-1-i];
}
for (int x = 0; i < N; i++)
{
newArr[i] = arr[x];
x++;
}
for (i = 0; i < N; i++)
{
printf("%d ", newArr[i]);
}
return 0;
}
Thank you guys, for all the comments and answers. I've tried them and they worked.
I have found a way to do it as well. It's bit different. I did it with a function which moves all the elements with 1 position and then repeat the func as much as needed (K times).
#Cheatah helped me come up with it. I will post it in case somebody likes this solution in the future.
Here it is:
#include <stdio.h>
#include <stdlib.h>
int moveOnePos(int num, int array[num])
{
int temp = array[num - 1];
for (int b = num - 1; b > 0; b--)
{
array[b] = array[b - 1];
}
array[0] = temp;
return 0;
}
int main()
{
int N, K, i;
printf("Please enter size of array: ");
scanf("%d", &N);
printf("Please enter K: ");
scanf("%d", &K);
int arr[N];
for (i = 0; i < N; i++)
{
scanf("%d", &arr[i]);
}
for (i = 0; i < K; i++)
{
moveOnePos(N, arr);
}
for (i = 0; i < N; i++)
{
printf("%d", arr[i]);
}
return 0;
}

Creating dynamic two dimensional array in C

I want to write a program that calculates a matrix multiplication.
However, it seems like there is a problem concerning the memory allocation. For m <= 2 and n <= 2, the code works just fine but after staring at it for an hour, I still can't figure out why the program blows up vor values greater than that (SegFault and free_matrix() is complaining about trying to free not allocated memory).
Here is my Code:
#include <stdio.h>
#include <stdlib.h>
typedef double *Vector;
typedef Vector *Matrix;
//Initializes a matrix of given size
Matrix mat_alloc(int m, int n){
Matrix mat = NULL;
mat = (Matrix)malloc(sizeof(m * sizeof(Vector)));
if(mat == NULL){
printf("Error: Not Enough Memory!\n");
return NULL;
}
for(int i = 0; i < m; i++){
mat[i] = (Vector)malloc(n * sizeof(double));
if(mat[i] == NULL){
printf("Error: Not Enough Memory!\n");
return NULL;
}
}
return mat;
}
Matrix mat_mult(Matrix A, Matrix B, int m, int n, int k){
Matrix C = mat_alloc(m, k);
for(int i = 0; i < m; i++){
for(int j = 0; j < k; j++){
C[i][j] = 0;
for(int l = 0; l < n; l++){
C[i][j] += A[i][l] * B[l][j];
}
}
}
return C;
}
void print_matrix(Matrix mat, int m, int n){
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
printf("%.2lf ", mat[i][j]);
}
printf("\n");
}
}
void read_matrix(Matrix mat, int m, int n){
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
printf("(%d,%d) = ", i+1, j+1);
scanf("%lf", &mat[i][j]);
}
}
}
void free_matrix(Matrix mat, int m){
for(int i = 0; i < m; i++){
free(mat[i]);
}
free(mat);
}
int main(int argc, char *argv[]){
int m = 0;
int n = 0;
int k = 0;
printf("Dimensions of A (m x n):\n");
printf("m = ");
scanf("%d", &m);
printf("n = ");
scanf("%d", &n);
printf("Dimensions of B (n = %d x k):\n", n);
printf("k = ");
scanf("%d", &k);
printf("Your input: m = %d, n = %d, k = %d\n", m, n, k);
Matrix A = NULL;
Matrix B = NULL;
Matrix C = NULL;
A = mat_alloc(m, n);
B = mat_alloc(n, k);
printf("Enter Values for A!\n");
read_matrix(A, m, n);
printf("Enter Values for B!\n");
read_matrix(B, n, k);
printf("A = \n");
print_matrix(A, m, n);
printf("\nB = \n");
print_matrix(B, n, k);
C = mat_mult(A, B, n, m, k);
printf("\nC = \n");
print_matrix(C, m, k);
free_matrix(A, m);
free_matrix(B, n);
free_matrix(C, m);
return 0;
}
Thank you in advance.
This here:
mat = (Matrix)malloc(sizeof(m * sizeof(Vector)));
Should be
mat = (Matrix)malloc(m * sizeof(Vector));
Or better yet
mat = malloc(sizeof *mat * m);
You have a sizeof too much, so instead of getting the desired size of the pointer array, you get a constant (the size of a size_t).

Error in a C program using dynamic memory allocation and array

Programming in C for finding maximum in 2D array using dynamic memory allocation.
int main() {
int i, arr[m][n], j, m, n;
int max = 0;
int *ptr;
printf("enter the value m");
scanf("%d", m);
printf("enter the vaue of n");
scanf("%d", n);
ptr = (int*) malloc(m * n * 4);
printf("enter the values\n");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
scanf("%d", ((ptr + i * n) + j));
}
}
max = arr[0][0];
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
if (max < *((ptr + i * n) + j));
max = *((ptr + i * n) + j);
}
}
printf("%d", max);
}
I made changes to your code to remove the error you are getting. I commented the changes that I have made.
int main()
{
/*int i, arr[][], j, m, n;*/
/* Because arr is allocated dynamically, you have to declare as a pointer to int. */
int i, *arr, j, m, n;
int max = 0;
int *ptr;
printf("enter the value m");
scanf("%d", m);
printf("enter the vaue of n");
scanf("%d", n);
/*ptr = (int*)malloc(m * n * 4);*/
/* It is better to use sizeof(int) because int does not have the same length of all computers. */
ptr = (int*)malloc(m * n * sizeof(int));
printf("enter the values\n");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
scanf("%d", ((ptr + i * n) + j));
}
}
/*max = arr[0];*/
/* To get the first int at arr, you could also use arr[0], but not arr[0][0] because */
/* this would require that arr be an array of pointers to array of int's, which is not the case. */
max = *arr;
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
if (max < *((ptr + i * n) + j));
max = *((ptr + i * n) + j);
}
}
printf("%d", max);
}
You must learn the algorithms and programming language C.
So you can find some courses in this site :
learn-c
try this code is functioned:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[]) {
int i, j, m, n;
int max;
int **ptr;
printf("enter the value m: ");
scanf("%d", &m);
printf("enter the vaue of n: ");
scanf("%d", &n);
ptr = (int **)malloc(n * sizeof(int *));
for (i = 0; i < m; i++) {
*(ptr + i) = (int *)malloc(m * sizeof(int));
for (j = 0; j < n; j++) {
scanf("%d", (*(ptr + i) + j));
}
}
max = **ptr;
printf("\n\nMatrix:\n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
printf("%d ", *(*(ptr + i) + j));
if (max < *(*(ptr + i) + j))
max = *(*(ptr + i) + j);
}
printf("\n");
}
printf("\nthe max is %d \n", max);
return 0;
}

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