This is the code i wrote for multiple occurrences in linear search.Can you please help me point out the mistake ? I want the function to store multiple values in the pointer array and then later to print the array
#include <stdio.h>
void linearsearch(int n,int a[n],int x,int count,int *b[count])
{
count=0;
int i;
for(i=0;i<n;i++)
{
if(a[i]==x)
{
count+=1;
}
}
int j=0;
for(i=0;i<n;i++)
{
if(a[i]==x)
{
b[j]=i;
j++;
}
}
}
int main()
{
int n;
scanf("%d",&n);
int a[n];
int i;
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
int x;
scanf("%d",&x);
int count;
int *b[count];
linearsearch(n,a,x,count,b);
for(i=0;i<count;i++)
{
printf("%d",*b[i]);
}
return 0;
}
I think there are several errors.
count must be initialized, like int count = 0;
count variable is not changed after linearsearch function.
b array should allocated dynamically.
suggested patch is:
#include <stdio.h>
void linearsearch(int n,int a[n],int x,int *count,int **b)
{
count=0;
int i;
for(i=0;i<n;i++)
{
if(a[i]==x)
{
count+=1;
}
}
int j=0;
for(i=0;i<n;i++)
{
if(a[i]==x)
{
*b = realloc(*b, sizeof(int) * (j + 1));
(*b)[j]=i;
j++;
}
}
}
int main()
{
int n;
scanf("%d",&n);
int a[n];
int i;
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
int x;
scanf("%d",&x);
int count = 0;
int *b = NULL;
linearsearch(n,a,x,&count,&b);
for(i=0;i<count;i++)
{
printf("%d",b[i]);
}
return 0;
}
Well the ideal way would be to allocate the memory dynamically based of the number of x found. But well let's look at the errors first. Maybe after this discussion you can write the code.
b[j]=i;
In the called function let's dissect the type of this.
i is of type int. And b[j] is of type int*. Then you assigned them (type mismatched). Then %d expects an int but you passed something of type int*. This is undefined behavior.
Now there was another flaw you had - you passed count and somehow you expect the value you changed in search will be there in main(). C is pass by value and you changed to a local variable. That change is lost when the called function ends.
#include <stdio.h>
#include <stdlib.h>
int* linearsearch(int n,int* a,int x,int* count)
{
*count=0;
if( n <= 0){
fprintf(stderr, "%s\n","Error" );
exit(1);
}
int *t = malloc(sizeof(*t)*n);
if( t == NULL){
perror("Malloc failed");
exit(1);
}
for(int i = 0; i < n; i++)
if(a[i] == x)
t[(*count)++] = i;
int *temp = realloc(t,sizeof(*temp)* (*count));
if( temp == NULL){
perror("Realloc failed");
exit(1);
}
t = temp;
return t;
}
int main(void)
{
int n;
if( scanf("%d",&n)!= 1){
fprintf(stderr, "%s\n", "Error in input");
exit(1);
}
if( n <= 0 ){
fprintf(stderr, "%s\n", "Error in input : must be greater than 0");
exit(1);
}
int a[n];
for(int i=0; i < n; i++)
if(scanf("%d",&a[i])!=1){
fprintf(stderr, "%s\n","Error in input." );
exit(1);
}
int elmt_to_find;
if( scanf("%d",&elmt_to_find)!= 1){
fprintf(stderr, "%s\n", "Error in input : Element to find(must be integer)");
}
int count;
int *b = linearsearch(n,a,elmt_to_find,&count);
for(int i = 0; i < count; i++)
printf("%d ",b[i]);
printf("%s","\n");
free(b);
return 0;
}
If you want to stick with using VLA for b, you can alter your linearsearch to return count only if b is NULL. Then, you can create b as VLA, and pass it back to linearsearch again to be populated.
int count = linearsearch(n, a, x, 0, 0);
int b[count];
linearsearch(n, a, x, count, b);
Then, your function could look like:
int linearsearch(int n,int a[n],int x,int count,int *b[count])
{
int i;
if(count==0)
{
for(i=0;i<n;i++)
{
if(a[i]==x)
{
count+=1;
}
}
}
if (b==0)
{
return count;
}
int j=0;
for(i=0;i<n;i++)
{
if(a[i]==x)
{
b[j]=i;
j++;
}
}
return count;
}
Related
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;
}
I am trying to write a program which calculates some bags and weights. I wrote it without using functions but I have to use functions and I am really bad at it.
The code normally works, but I just can't implement it with functions. It stops working after printing array A, and just 0s when printing array B.
My code is:
#include <stdio.h>
#include <math.h>
int f1(int N);
int f2(int N);
int f3(int N, float A[20]);
int main(void)
{
int N;
f1(N);
return 0;
}
int f1(int N)
{
for(;;)
{
printf("Enter N(the number of bags) (Between 1 and 20): ");
scanf("%d", &N);
if (N < 1 || N > 20)
{
continue;
}
else
{
break;
}
}
f2(N);
}
int f2(int N)
{
float A[20];
int i;
for(i=0; i<N;i++)
{
printf("Enter the weight of the bag with potatoes %d: ", i+1);
scanf("%f", &A[i]);
}
printf("\n\nThe weights of the initial bags (the A array):\n");
for(i=0; i<N;i++)
{
printf("%.1f " ,A[i]);
}
f3(N, &A[20]);
}
int f3(int N, float A[20])
{
int i;
float B[10];
printf("\n\nNow we equalize the weights of bags.\n");
if (N%2 == 0)
{
for(i=0;i<N/2 ;i++)
{
B[i] = fabsf(A[i] - A[N-1-i]);
}
}
else
{
for(i=0;i<N/2 ;i++)
{
B[i] = fabsf(A[i] - A[N-1-i]);
}
B[N/2] = A[N/2];
}
if (N%2 == 0)
{
for (i=0; i<N/2; i++)
{
if (A[i] < A[N-1-i])
{
A[N-1-i] = A[i];
}
else
{
A[i] = A[N-1-i];
}
}
}
else
{
for (i=0; i<N/2; i++)
{
if (A[i] < A[N-1-i])
{
A[N-1-i] = A[i];
}
else
{
A[i] = A[N-1-i];
}
}
A[N/2] = 0;
}
printf("\nThe weights of the new bags (the B array):\n");
if (N%2 == 0)
{
for(i=0; i<N/2 ;i++)
{
printf("%.1f " ,B[i]);
}
}
else
{
for(i=0; i<N/2 ;i++)
{
printf("%.1f " ,B[i]);
}
printf("%.1f", B[N/2]);
}
printf("\nThe new weights of the initial bags (the A array):\n");
for(i=0;i<N;i++)
{
printf("%.1f ", A[i]);
}
}
To pass an array to a function just use its name.
f3(N, &A[20]);
should be
f3(N, A);
To pass an array or pointer as an argument when calling a function in C, you just need to pass it name, in your case,
f3(N, A);
Also, when declaring the function, the length of the array doesn't matter, because C performs no bounds checking for formal parameters. Although it will work this way, it is best to change
int f3(int N, float A[20])
to
int f3(int N, float A[])
or
int f3(int N, float* A)
I am trying to write a program in C to create a union between two arrays, then output the total number of elements in the new array. I am getting the following errors when compiling my code (gcc).
test.c:44:11: error: expected ‘{’ before ‘(’ token
void union(int arrA[], int arrB[], int m, int n)
^
test.c:44:6: error: two or more data types in declaration specifiers
void union(int arrA[], int arrB[], int m, int n)
^
I've checked through for missing semicolons, etc. So unless I'm just missing it, I can't figure out where the issue is coming from. Any help would be appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int n;
int m;
int i;
int k;
printf("Enter the size of array A: ");
scanf("%d",&n);
int arrA[n];
printf("Enter the element(s) of array A: ");
for(i=0;i<n;i++)
{
scanf("%d",&arrA[i]);
}
for(i=0; i<n; i++)
{
printf("%d",arrA[i]);
}
printf("\n");
printf("Enter the size of array B: ");
scanf("%d",&m);
int arrB[m];
printf("Enter the element(s) of array B: ");
for(i=0;i<m;i++)
{
scanf("%d",&arrB[i]);
}
for(i=0; i<m; i++)
{
printf("%d",arrB[i]);
}
printf("\n");
printf("%d\n",k);
return 0;
}
int union(int arrA[], int arrB[], int m, int n)
{
int i = 0;
int j = 0;
int k = 0;
int l = 0;
if(n > m)
{
n = l;
}
else
{
m = l;
}
int arrC[l];
while ((i < n) && (j < m))
{
if (arrA[i] < arrB[j])
{
arrC[k] = arrA[i];
i++;
k++;
}
else if (arrA[i] > arbB[j])
{
arrC[k] = arrB[j];
j++;
k++;
}
else
{
arrC[k] = arrA[i];
i++;
j++;
k++;
}
}
if (i == n)
{
while (j < m)
{
arrC[k] = arrB[j];
j++;
k++;
}
}
else
{
while (i < n)
{
arrC[k] = arrA[i];
i++;
k++;
}
}
return(k);
}
As pointed out by sawims in the comments, union is a reserved word and you had a typo on else if (arrA[i] > arbB[j]), changing the function's name and fixing the typo your code compiles.
http://ideone.com/ubB1eG
So a user can create his square matrix and enter the desired values. The thing is that the matrix is created via a function and it seems that when the function is done with its task and we return to the main function and I try to reprint the elements of the matrix,to check if everything is ok again after the first printing inside the function, the program crashes. Have in mind that I'm using pointers only and not []s. Also the size variable is going to be used in functions that check various properties of the matrix(sparse etc) so that's why I use it like this.
#include <stdio.h>
#include <stdlib.h>
int CreateArray(int **ptr);
int main()
{
int **ptr = NULL;
int size = 0;
int i,j;
size = CreateArray(ptr);
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
printf("%d",*(*(ptr+i)+j));
if(j == (size-1))
{
printf("\n");
}
}
}
system("PAUSE");
return 0;
}
int CreateArray(int **ptr)
{
int i=0;
int j=0;
int size = 0;
printf("Input the size of your square matrix\n");
scanf("%d", &size);
ptr = malloc(sizeof(int*)*size);
for(i=0; i< size; i++)
{
*(ptr + i) = malloc(sizeof(int)*size);
}
printf("Enter the values to be stored in your array\n");
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
scanf("%d", &*(*(ptr+i)+j));
}
}
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
printf("%d",*(*(ptr+i)+j));
if(j == (size-1))
{
printf("\n");
}
}
}
return size;
}
Your pointer is passed by value. If you want to modify from within the function, you need to pass its address. You then need to re-adjust all lines within CreateArray that accessed ptr to dereference it once more:
int main()
{
int **ptr = NULL;
int size = 0;
int i,j;
size = CreateArray(&ptr);
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
printf("%d ",*(*(ptr+i)+j));
if(j == (size-1))
{
printf("\n");
}
}
}
return 0;
}
int CreateArray(int ***ptr)
{
int i=0;
int j=0;
int size = 0;
printf("Input the size of your square matrix\n");
scanf("%d", &size);
*ptr = malloc(sizeof(int*)*size);
for(i=0; i< size; i++)
{
*((*ptr) + i) = (int*)malloc(sizeof(int)*size);
}
printf("Enter the values to be stored in your array\n");
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
scanf("%d", (*((*ptr)+i)+j));
}
}
return size;
}
I got a problem in generating an array of integers. the program fills hundreds of cells of the array with numbers like -32429173 instead of 3 cells with numbers from 0 to 3 (for example). Maybe the problem is in the wrong way of allocating memory? Here is the wrong part of the code. Thx for the help in advance.
int* generate()
{
int maxnumb;
int i;
scanf_s("%d",&size); //size of an array
scanf_s("%d",&maxnumb); //asks for maxnumb to fill the array with random numbers from 0 to maxnumb
int* array=(int*)calloc(size,sizeof(int));
for (i=0;i<size;i++)
array[i] = rand() % maxnumb + 1;
return array;
}
Here is the full code
#define _CRT_SECURE_NO_WARNINGS
#include<stdlib.h>
#include<stdio.h>
int size;
void swap(int* elem1,int* elem2) //swap elements
{
int temp;
temp=*elem1;
*elem1=*elem2;
*elem2=temp;
}
void bublesort(int* array,int size) //bublesort
{
for (int j=1;j<size-1;++j)
{
for (int i=0;i<size-j;++i)
{
if ((array[i])>(array[i+1]))
swap(&array[i],&array[i+1]);
}
}
}
int* enterHand() //handle entering
{
int i;
scanf_s("%d",&size);
int* array=(int*)calloc(size,sizeof(int));
for (i=0;i<size;i++)
{
scanf_s("%d",&array[i]);
}
return array;
}
int* enterFile() //entering from the file
{
int i;
int singlenumb;
FILE* foo;
errno_t err;
err=fopen_s(&foo,"input.txt","r");
if( err == 0 )
{
printf( "The file 'input.txt' was opened\n" );
}
else
{
printf( "The file 'input.txt' was not opened\n" );
}
while (!feof(foo))
{
fscanf_s(foo, "%d", &singlenumb);
size++;
}
size-=1;
int* array=(int*)calloc(size,sizeof(int));
rewind(foo);
i=0;
while (i!=size)
{
fscanf_s(foo, "%d", &array[i]);
i++;
}
fclose(foo);
return array;
}
int* generate()
{
int maxnumb;
int i;
scanf_s("%d",&size); //size of an array
scanf_s("%d",&maxnumb); //asks for maxnumb to fill the array with random numbers from 0 to maxnumb
int* array=(int*)calloc(size,sizeof(int));
for (i=0;i<size;i++)
array[i] = rand() % maxnumb + 1;
return array;
}
void putsFile(int* array, int size)
{
int i=0;
int k;
FILE* fooo;
fopen_s(&fooo,"output.txt","w");
while (i!=size)
{
for (k=0; k<10; k++)
{
fprintf(fooo,"%d ", array[i]);
i++;
}
fprintf(fooo,"\n");
}
fclose(fooo);
}
void printArray(int* array, int size)
{
int i=0;
int k;
while (i!=size)
{
for (k=0; k<10; k++)
{
printf("%d ", array[i]);
i++;
}
printf("\n");
}
}
int main()
{
int choice;
int* pntr;
printf("choose a type of filling an array\n1 = handle filling\n2 = filling from the file\n3 = generating\nenter the number...\n");
scanf("%d", &choice);
switch (choice)
{
case 1: {pntr=enterHand();} break;
case 2: {pntr=enterFile();} break;
case 3: {pntr=generate();} break;
default: {pntr=NULL;}
}
bublesort(pntr,size);
printf("choose a type of typing an array\n1 = console\n2 = file\nenter the number...\n");
scanf("%d", choice);
switch (choice)
{
case 1: {printArray(pntr, size);} break;
case 2: {putsFile(pntr, size);} break;
default: {printf("you entered the wrong number");}
}
return 0;
}
I think you should initialize your maxnumb
First, here is a simpler approach for filling an array.
int randomGenerator(int min, int max);
int main(void)
{
int array[100]//or any size
for(i=0;i<sizeof(array)/sizeof(array[0]);i++)
{
array[i]=randomGenerator(1,3);//will issue only 1, 2 or three (as you requested)
} //change min and max for wider range
return 0;
}
int randomGenerator(int min, int max) //set the range of desired numbers in array
{
int random=0, trying=0;
trying = 1;
while(trying)
{
srand(clock());
random = (rand()/32767.0)*(max+1);
(random >= min) ? (trying = 0) : (trying = 1);
}
return random;
}
There are also some things you can do to make this non-repeating, i.e. so you won't get two Ace of Spades. But for now, you have much bigger issues...
Your code, as is has too many issues to build. If you post a small, buildable section, with the specific problem, it can be better addressed.
The printArray() and putsFile() may print outside array size.
int* enterFile() does not set size to 0 before determining number of int in the file, thus using a potentially unexpected non-zero size.
[Edit] Well size is implicitly set to 0 being in the global uninitialized space. Still, recommend explicitly setting to 0 in enterFile().
#if 0
// The value of size is dependent on program history or uninitialized.
while (!feof(foo)) {
fscanf_s(foo, "%d", &singlenumb);
size++;
}
size-=1;
#else
size = 0; // Reset size to 0
while (1 == fscanf_s(foo, "%d", &singlenumb)) {
size++;
}
#endif
Suggest:
void printArray(int* array, int size) {
// Also in void putsFile(int* array, int size)
int i=0;
while (i < size) {
int k;
for (k=0; k<10; k++) {
printf("%d ", array[i]);
i++;
// Add
if (i >= size) break;
}
printf("\n");
}
}