Returning array made with calloc to main - c

So I have a problem:
My program has to find the most common element in an array. We have to make this array with calloc. My code is working but I am asked to move part of my code to a function in which I have to create an array and enter numbers.
int main() {
int n, i, dazn;
int *A;
dazn = 0;
printf("Iveskite naturalu skaiciu: \n");// enter how many elements in an array we will have
scanf("%d", &n);
A = (int*)calloc(n, sizeof(int)); // Starting from here...
for (i = 0; i < n; i++) {
printf("Iveskite skaiciu \n");
scanf("%d", &A[i]); //
}
... // and ending here have to be in a function
... // sorting and finding the most common element

As instructed, move the code to a separate function:
#include <stdio.h>
#include <stdlib.h>
int *allocate_and_read_array(int size) {
int *A = (int*)calloc(size, sizeof(int));
if (A != NULL) {
for (int i = 0; i < size; i++) {
printf("Iveskite skaiciu \n");
if (scanf("%d", &A[i]) != 1) {
printf("Missing values\n");
break;
}
}
}
return A;
}
int main(void) {
int n, i, dazn;
int *A;
dazn = 0;
printf("Iveskite naturalu skaiciu: \n");// enter how many elements in an array we will have
scanf("%d", &n);
A = allocate_and_read_array(n);
... // sort the array
... // find the most common element
free(A);
return 0;
}

Related

How to print elements from another function into main function

I can't figure out how to print array elements from my function into the main program so if some can examine this code and help me fix it I would appreciate it. The program is supposed to take the length of the array from user input and then ask for its elements and print them out afterward.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int arrayN(int N) {
printf("Input array lenght: ");
scanf("%d",&N);
if(N>2) {
return N;
} else {
return 0;
}
}
int arrayelements(int array[], int array_length) {
int loop, i, N;
array_length = arrayN(N);
printf("Enter elements of the array: \n");
for(int i = 0; i < array_length; ++i) {
scanf("%d", &array[i]);
}
for(loop = 0; loop < array_length; loop++) {
printf("%d ", array[loop]);
}
}
int main() {
int N, array[], array_length;
int b = arrayelements(array[], array_length);
int a = arrayN(N);
printf("Array length is: %d \n", a);
printf("Elements of array are: %d \n", b);
return 0;
}
I reworked your example code. Hope it is what you want.
Focus lied on fixing the array declaration issues, memory allocation and
user input.
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <ctype.h>
int userinput_integer(const char *fmt, ...){
int N, rv = 0;
va_list va;
va_start(va, fmt);
vprintf(fmt, va);
while(1){
rv = scanf("%d", &N);
if (1 == rv) break;
printf("Input error! The input >>");
do{
rv = fgetc(stdin);
if (isprint(rv)) putchar(rv);
}while(rv != EOF && rv != '\n');
printf("<< is not a valid integer.\nPlease try again: ");
}
va_end(va);
return N;
}
int userinput_arraylength(void) {
int N;
N = userinput_integer("Input array lenght: ");
if(N>2) {
return N;
} else {
printf("Invalid length\n");
return 0;
}
}
int userinput_arrayelements(int *array, int N) {
printf("Enter elements of the array: \n");
for(int i = 0; i < N; ++i) {
array[i] = userinput_integer("%d: ", i);
}
return N;
}
void print_arrayelements(int *array, int N){
for(int i = 0; i < N; ++i) {
printf("%d ", array[i]);
}
}
int main() {
int N, *array;
N = userinput_arraylength();
array = malloc(N * sizeof(*array));
if (NULL == array){
printf("Allocation error!\n");
exit(-1);
}
N = userinput_arrayelements(array, N);
printf("Array length is: %d \n", N);
printf("Elements of array are:\n");
print_arrayelements(array, N);
free(array);
return 0;
}
Fistly, declaration of array is not correct.
It should be array[] = {0}
Secondly, you cannot call your array elements function before arrayN function, the size of array should be entered first
And in the array elements() there is no need to call the size function you can directly pass the size of array when calling the array elements ()
Here's the code:
#include <stdio.h>
#include<malloc.h>
int *getarray()
{
int size;
printf("Enter the size of the array : ");
scanf("%d",&size);
int *p= malloc(sizeof(size));
printf("\nEnter the elements in an array");
for(int i=0;i<size;i++)
{
scanf("%d",&p[i]);
}
return p;
}
int main()
{
int *ptr;
ptr=getarray();
int length=sizeof(*ptr);
printf("Elements that you have entered are : ");
for(int i=0;ptr[i]!='\0';i++)
{
printf("%d ", ptr[i]);
}
return 0;
}

Adding the same number multiple times to an empty array in C

This is a piece of code to add the same number multiple times to an empty array but when I am printing the now non empty array, I am getting some other values:
#include<stdio.h>
#include<stdlib.h>
void sort_0(int arr[100], int i, int n){
int final_array[100], c=0;
// Count the number of '0' in the array
for(i=0;i<n;i++){
if(arr[i] == 0){
c++;
}
}
// Add the c number of '0' to the final_array
for(i=0;i<c;i++){
scanf("%d",final_array[i]);
}
for(i=0;i<c;i++){
printf("%d ", final_array[i]);
}
}
int main(){
int arr[100], i, n;
// Entering the size of the array
scanf("%d", &n);
// Entering n elements into the array
for(i=0;i<n;i++){
scanf("%d", &arr[i]);
}
sort_0(arr,i,n);
return 0;
}
In the above code, the number of times 0 appears in the array is counted. Then the count is taken as the range and 0 is adding to the empty array final_array count times.
If c = 5, the final_array = {0,0,0,0,0}
Expected Output:
arr = {0,1,4,3,0}
Output = 2
I am not getting any output
Since you don't know how much 0 you'll need to add to your array_final I figured out that a better solution could be to create that array after you have the number of 0 of the first array. Also, I see no reason why you were passsing i to the function since you can simply define it in the function itself.
void sort_0(int arr[10], int n, int* c){
int i;
for(i=0;i<n;i++){
if(arr[i] == 0){
(*c)+= 1;
}
}
}
int main (void) {
int size;
printf("Enter array size: ");
scanf("%d", &size);
int arr[size];
for (int i=0;i<size;i++) {
scanf("%d",&arr[i]);
}
int c = 0;
sort_0(arr, size, &c);
printf("C is: %d\n",c);
int* final_array;
if ((final_array=malloc(c * sizeof(int)))==NULL) // should always check malloc errors
{
perror("malloc");
return -1;
}
for (int i=0;i<c;i++) {
final_array[i]= 0;
}
printf("{");
for (int i=0;i<c-1;i++) {
printf("%d,", final_array[i]);
}
printf("%d}\n",final_array[c-1]);
return 0;
}

Function call in C with array

I have a function that takes array 1 and copies/manipulates it to array 2. Basically what it does is take the user input in array one, lets say (2, 3, 3) and array 2 is stored as (2, 0, 3, 0, 3). I know this works because it worked without implementing a function but sadly I have to have one. I cannot for the life of me figure out how to call the function, I believe I don't need a return since its a void and not returning a value. Below is my code any help would be appreciated.
#include <stdio.h>
void insert0(int n, int a1[], int a2[]);
int main() {
int i = 0;
int n = 0;
int a1[n];
int a2[2*n];
printf("Enter the length of the array: ");
scanf("%d",&n);
printf("Enter the elements of the array: ");
for(i = 0; i < n; i++){ //adds values to first array
scanf("%d",&a1[i]);
}
insert0(); //call function which is wrong and I cannot get anything to work
for( i = 0; i < n*2; i++){ //prints array 2
printf("%d", a2[i]);
}
void insert0 (int n, int a1[], int a2[]){ //inserts 0's between each number
for(i = 0; i < n; i++){
a2[i+i] = a1[i];
a2[i+i+1] = 0;
}
}
}
Modifying n after declaraing a1 and a2 won't magically increase their size. Declare a1 and a2 after reading the size into n to use variable-length arrays.
You must pass proper arguments to call insert0.
Defining functions inside functions is GCC extension and you shouldn't do that unless it is required.
a2 should have n*2 - 1 elements, not n*2 elements.
After moving it out of main(), i is not declared in insert0, so you have to declare it.
You should check if readings are successful.
Corrected code:
#include <stdio.h>
void insert0(int n, int a1[], int a2[]);
int main() {
int i = 0;
int n = 0;
printf("Enter the length of the array: ");
if(scanf("%d", &n) != 1){
puts("read error for n");
return 1;
}
if(n <= 0){
puts("invalid input");
return 1;
}
int a1[n];
int a2[2*n-1];
printf("Enter the elements of the array: ");
for(i = 0; i < n; i++){ //adds values to first array
if(scanf("%d", &a1[i]) != 1){
printf("read error for a1[%d]\n", i);
return 1;
}
}
insert0(n, a1, a2);
for( i = 0; i < n*2-1; i++){ //prints array 2
printf("%d", a2[i]);
}
}
void insert0 (int n, int a1[], int a2[]){ //inserts 0's between each number
int i;
for(i = 0; i < n; i++){
a2[i+i] = a1[i];
if (i+1 < n){ // don't put 0 after the last element
a2[i+i+1] = 0;
}
}
}

Call a function that receives an array using a pointer

So I've this:
int main()
{
int workers;
printf("How many workers are there?\n");
scanf("%d", &workers);
printf("What are their preferences?\n");
int *pref = malloc(workers * sizeof(int));
if (pref == NULL)
return -1;
fillPreferences(pref, workers);
return 0;
}
I want now to fill the "pref" 2d array in this function:
void fillPreferences(int pref[][], int size)
{
for (int i=0;i<size;i++)
{
for (int j=0;j<size;j++)
{
scanf(" %d", &pref[i][j]);
}
}
}
It doesn't work, probably because I'm using the pointer wrong. How can I use malloc and then call a function and receive the values in the 2d array by doing pref[i][j]? (Note that I'm not looking to do something like scanf(..., &pref+i) or whatever. I need to actually use that 2d array.
Thanks :)
When you write a[i], it is turned into *(a+i). That is, a[i] accesses the memory by a+i address (well, it is a+i*sizeof(element) even).
As such, a[i][j] means *(*(a+i)+j). Two memory accesses. For this to work, your a should be an array of arrays. That is, you need to malloc its elements first and then malloc a memory to hold them.
In your particular case, i doubt you need it. What you need is make it 1D-array (which is it already) and calculate index from your two indices in whatever fashion you wish.
Your pref array is 1D so you can make it in this way:
#include <stdio.h>
#include <stdlib.h>
void fillPreferences(int **pref, int size)
{
int prefNum=0;
for (int i=0;i<size;i++)
{
puts("Number of preferences");
scanf("%d",&prefNum);
pref[i]=malloc(sizeof(int)*prefNum);
puts("Enter preferences");
for(int j=0;j<prefNum;j++){
scanf(" %d", &pref[i][j]);
}
}
}
int main()
{
int workers;
printf("How many workers are there?\n");
scanf("%d", &workers);
printf("What are their preferences?\n");
int **pref = malloc(workers * sizeof(int *));
if (pref == NULL)
return -1;
fillPreferences(pref, workers);
// Show values
printf("%d %d %d",pref[0][0],pref[1][0],pref[2][0]);
return 0;
}
You allocate memory for a 1D array, but the function you have is designed to accept a 2D array and fill it (although the function definition is incorrect and won't compile).
Corrected code:
#include <stdio.h>
#include <stdlib.h>
void fillPreferences(int** pref, int size)
{
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
scanf("%d", &pref[i][j]);
}
}
}
int main()
{
int workers;
printf("How many workers are there?\n");
scanf("%d", &workers);
printf("What are their preferences?\n");
int **pref = malloc(workers * sizeof(int*));
if (pref == NULL)
return -1;
for(int i = 0; i < workers; i++)
{
pref[i] = malloc(workers * sizeof(int));
if(pref[i] == NULL)
{
for(int j = 0; j < i; j++)
free(pref[j]);
free(pref);
return -1;
}
fillPreferences(pref, workers);
/* Don't forget to `free` everything after its use! */
return 0;
}

How to print array returned from function

This code is supposed to recieve to arrays and then call function to return them in 1 array but I don't know how to print the last array returned from the function thanks in advance ???
and now I write anything because it says that the post is mostly code :D :D
#include <stdio.h>
#include <stdlib.h>
int join_arrays(int *array1, int *array2, int arr1_size, int arr2_size);
int main() {
int size_arr1, size_arr2, i, num1 = 1, s;
printf("Please enter the size of the first array: ");
scanf("%d", &size_arr1);
int arr1[size_arr1];
printf("start fill your first array: \n");
for (i = 0; i < size_arr1; i++) {
printf("enter element number %d: ",num1);
scanf("%d", &arr1[i]);
num1++;
}
num1 = 1;
printf("Please enter the size of the second array: ");
scanf("%d", &size_arr2);
int arr2[size_arr2];
int *ptr1_last;
printf("start fill your second array: \n");
for (i = 0; i < size_arr2; i++) {
printf("enter element number %d: ", num1);
scanf("%d", &arr2[i]);
num1++;
}
ptr1_last = join_arrays(arr1, arr2, size_arr1, size_arr2);
printf("sorted array= \n");
for (s = 0; s < (size_arr1 + size_arr2); s++) {
printf("%d\n", ptr1_last);
}
return 0;
}
int join_arrays(int *array1, int *array2, int arr1_size, int arr2_size) {
int counter_arr1, counter_arr2, m = 0;
int last_arr[arr1_size + arr2_size];
for (counter_arr1 = 0; counter_arr1 < arr1_size; counter_arr1++) {
last_arr[counter_arr1]=array1[counter_arr1];
}
for (counter_arr2 = counter_arr1; counter_arr2 < (arr1_size + arr2_size); counter_arr2++) {
last_arr[counter_arr2] = array2[m];
m++;
}
return last_arr[0];
}
Modified the code to create the receiving array in main and pass a pointer to it to the merge function because the local array last_arr would no longer exist when the function returned in your code.
#include <stdio.h>
#include <stdlib.h>
//Prototype changed to include a pointer to the receiving array, also no longer returns a value.
void join_arrays(int *last_arr, int *array1,int *array2,int arr1_size,int arr2_size);
int main()
{
int size_arr1,size_arr2,i,num1=1,s;
printf("Please enter the size of the first array: ");
scanf("%d",&size_arr1);
int arr1[size_arr1];
printf("start fill your first array: \n");
for(i=0; i<size_arr1; i++)
{
printf("enter element number %d: ",num1);
scanf("%d",&arr1[i]);
num1++;
}
num1=1;
printf("Please enter the size of the second array: ");
scanf("%d",&size_arr2);
int arr2[size_arr2];
int *ptr1_last;
printf("start fill your second array: \n");
for(i=0; i<size_arr2; i++)
{
printf("enter element number %d: ",num1);
scanf("%d",&arr2[i]);
num1++;
}
int last_arr[size_arr1 + size_arr2]; //Create receiving array here
join_arrays(last_arr, arr1,arr2,size_arr1,size_arr2); //And pass it to the function.
printf("merged array= \n");
for(s=0;s<(size_arr1+size_arr2);s++)
{
printf("%d\n", last_arr[s]);
}
return 0;
}
void join_arrays(int *last_arr, int *array1,int *array2,int arr1_size,int arr2_size)
{
int counter_arr1, m=0;
for(counter_arr1=0; counter_arr1<arr1_size; counter_arr1++)
{
last_arr[counter_arr1]=array1[counter_arr1];
}
for(; counter_arr1<(arr1_size+arr2_size); counter_arr1++)
{
last_arr[counter_arr1]=array2[m];
m++;
}
}
With that function you return only the first element of the last_array, you should create a global array so it's visible in all functions, or return a pointer of the last_array[0] position in memory

Resources