Unable to convert (int*) to int - c

I'm just trying to read the elements from a text file that has all the numbers and pass it as an argument to the "frequency()" function given below.However,It shows up an error saying that
"argument of type int is incompatible with argument of type (int*)" . I tried everything to convert (int*) to int but ended up miserably..below posted is my C code.
void main()
{
FILE*file = fopen("num.txt","r");
int integers[100];
int i=0;
int h[100];
int num;
int theArray[100];
int n,k;
int g;
int x,l;
while(fscanf(file,"%d",&num)>0)
{
integers[i]=num;
k =(int)integers[i];
printf("%d\n",k);
i++;
}
printf ("\n OK, Thanks! Now What Number Do You Want To Search For Frequency In Your Array? ");
scanf("\n%d", &x);/*Stores Number To Search For Frequency*/
frequency(k,n,x);
getch();
fclose(file);
}
void frequency (int theArray [ ], int n, int x)
{
int count = 0;
int u;
// printf("%d",n);
for (u = 0; u < n; u++)
{
if ( theArray[u]==x)
{
count = count + 1 ;
/*printf("\n%d",theArray[u]);*/
/* printf("\n%d",count);*/
}
else
{
count = count ;
}
}
printf ("\nThe frequency of %d in your array is %d ",x,count);
}
So the idea is that the elements read through "num.txt" are stored in an array 'k' and the same array has to be passed in the frequency function! However,in my case it is saying "argument of type int is incompatible with argument of type(int*).

frequency(k, n, x);
|
|
+---int ?
But
frequency (int theArray [ ], int n, int x)
|
|
+ accepts an int*
Call your function as
frequency ( integers, i, x );
You never initialized n and theArray in your main, simply declaring them will not magically pass them in other functions.

When you call the frequency function, you're passing in the int k as the first argument. I think it's worth correcting your statement that k is an array. It is not. You declare it as an int. This is where your type error is coming from because it expects an int * (because of the int[] argument).
Perhaps you mean to pass in integers instead of k?

Related

Function for addition and getting average of a user defined single dimensional array

This is the question "Write a function which gets an integer array and number of elements as parameters and calculates and displays sum and average of all the integers of the array in C language"
Below is the code which I have done, it's running but consists of bugs which give false answers
#include <stdio.h>
void SumAvg(int x, int arr[x]) {
int i, sum = 0;
float avg = 0;
for (i = 0; i < x; ++i) {
sum += arr[i];
}
avg = (float)sum / x;
printf("The sum is %d", sum);
printf("\nThe average is %.2f", avg);
}
int main() {
int x, i;
printf("Enter number of elements");
scanf("%d", &x);
int arr[x];
for (i = 0; i < x; ++i) {
printf("Enter integers for array[%d]", i + 1);
scanf("%d", &arr[i]);
}
SumAvg(x, arr[x]);
return 0;
}
First , your function calling is wrong .It should be SumAvg(x,arr) instead of SumAvg(x, arr[x]);.
also in function declaration , in some compiler void SumAvg(int x, int arr[x]) might be problematic.
For starters the function should be declared the following way
void SumAvg( const int arr[], size_t n );
That is the parameter that declares the array shall have the qualifier const because the array is not changed in the function.
The number of elements of the array should have the type size_t.
The function definition can look the following way
void SumAvg( const int arr[], size_t n )
{
long long int sum = 0;
for ( size_t i = 0; i < n; i++ )
{
sum += arr[i];
}
double avg = n == 0 ? 0 : ( double )sum / n;
printf( "The sum is %lld\n", sum );
printf( "The average is %.2f\n", avg );
}
That is within the function the variable sum should have the type long long int to decrease the risk of overflow.
In general the user can pass to the function the number of elements equal to 0. In this case if not to check this value the function will have undefined behavior.
This call of the function
SumAvg(x, arr[x]);
is invalid because instead of passing the array you are passing its non-existent element with the index x.
Taking into account the provided function definition above a valid call of the function will look like
SumAvg( arr, x );

Finding frequency of an integer in an array and calculating x to the nth power

I am trying to solve two different C problems and would like some help and advice in order to better understand how C works and if I'm on the right track with these.
First problem is: To write a function that counts the number of times the value (x) appears among the first (n) elements of an array and returns that count as the frequency of x in theArray. So, an example would be if the array being passed contained the values {5, 7, 23, 8, 23, 67, 23}. And n was 7 and x was 23, then it would return a value of 3 since 23 occurs 3 times within the first 7 elements of the array.
Here is what I have so far:
#include <stdio.h>
#define SIZE 20 /* just for example - function should work with array of any size */
int frequency (int theArray[], int n, int x)
{
int i;
int count = 0;
for (i = 0; i < n; i++)
{
if (theArray[i] == x)
{
count = count++;
}
}
return (count);
}
int main(void)
{
/* hard code n and x just as examples */
int n = 12; /* look through first 12 items of array */
int x = 5; /* value to find */
int numberFrequency;
long int theArray[SIZE] = {5,2,3,4,5,6,1,2,10,5,10,12,6,8,7};
numberFrequency = frequency (theArray[SIZE], n, x);
printf ("%i", numberFrequency);
return 0;
}
Currently I'm getting a run time error message and believe it has something to do with the for loop function.
Second problem is: Write a function that raises an integer to a positive integer power. Have the function return a long int, which represents the results of calculating x to the nth power. Do not use the C pow library function and do not use recursion!
My code so far:
#include <stdio.h>
int x_to_the_n (int x, int n)
{
int i;
long int result = 1;
if (n == 0)
{
return(result);
}
else
{
for (i = 0; i < n ; ++i)
{
/* equation here - How can I make (x*x*x*x*x*x,etc...? */
result = x*(n*x);
}
}
return (result);
}
int main(void)
{
int x =4;
int n =5;
long int result;
result = x_to_the_n (x, n);
printf ("%i", result);
return 0;
}
I can't use recursion so that is out of the question. So, I thought the next best thing would be a for loop. But I'm a little stuck in how I would go about making a for loop do (xxx*x....) based on value of (n). Any help and advice would be appreciated!
In the first problem you give an element after the array as a parameter to your function.
You define a long int array, and pass it into a function expecting an int array.
long int theArray[SIZE] = {5,2,3,4,5,6,1,2,10,5,10,12,6,8,7};
should be
int theArray[SIZE] = {5,2,3,4,5,6,1,2,10,5,10,12,6,8,7};
Instead of this:
numberFrequency = frequency (theArray[SIZE], n, x);
try this:
numberFrequency = frequency (theArray, n, x);
And replace:
count = count++;
with:
count++;

Comparing two arrays of integers and returning the subscript (C)

(a newer version of my program is right in the end)
I need to create a program with a function that compares two arrays of integers and returns the subscript of the first place they differ.
I have to use a sentinel value to indicate the end of valid input, rather than EOF, as a file cannot have two end-of-files.
Example of my desired input and output for my program:
Input 1:
3 4 5
3 4 6
Output 1:
2
Explanation: the third values of two arrays are different, so it prints the third subscript (counting as 0,1,2).
I looked over similar issues on stackoverflow. Many errors were fixed and now it lets me to compile a program, without giving me any errors or warnings. But it blinds me because I don't understand what exactly doesn't work.
My problem that I encounter:
When I press Enter button after the first value, the program stops working.
I assume my tableDiff function is wrong, however I copied it from teacher's notes. Unless I made a typo, there shouldn't be any difference.
Here is my submitted version:
/*
* A simple program to sort numbers in the correct order
*/
#include <stdio.h>
#include <stdlib.h>
#define MAX 10 //max elements in array
#define SENTINEL -999 //indicate the end of valid input
int main () {
int tableFill(int a[], int max);
int tableDiff (const int a[], const int b[], int n, int m);
void tablePrint (const int a[], const int b[], int n, int m);
int a[MAX];
int b[MAX];
int m,n,index;
m = tableFill(a, MAX);
n = tableFill(b, MAX);
tablePrint(a,b,n,m);
index = tableDiff(a,b,m,n);
if(index==-1)
printf("Index is the same");
else
printf("Index is the different");
return 0;
}
// read values from stdin into array up to 'max' values
int tableFill(int a[], int max) {
int r; // input from scanf
int next; // next input value
int cnt = 0; // count of values read
int *ptr; //pointer
printf("Enter the numbers! \n");
while ((r=scanf("%i", &next)) == 1 && next != SENTINEL)
{
if (r == 0) //invalid input data
{
printf("Nonnumeric data entered. Please enter a number. \n");
while (getchar()!= '\n'); // flush invalid data
}
else
*ptr++=cnt;
}
if(r==1) //another value was read but the array is full
printf("Error - too many values. Array size %i.\n", max);
return ptr-a; //(ptrb - b) should return the same value
}
int tableDiff (const int a[], const int b[], int n, int m)
{
const int *ptra = a; //start for 1st array
const int *ptrb = b; //start for 2nd array
const int *endptra = a+m; //end for 1st array
const int *endptrb = b+n; //end for 2nd array
while(ptra<endptra && ptrb<endptrb && *ptra==*ptrb)
{
ptra++;
ptrb++;
}
if( ptra==endptra && ptrb==endptrb)
{
return -1;
}
else
return ptra -a; //(ptrb - b) should return the same value
}
//print all elements in array.
void tablePrint (const int a[], const int b[], int n, int m)
{
int i; //varriable to print
for (i = 0; i < n; i++)
printf ("%d ", a[i]);
printf ("\n");
}
Here is my newer version:
The program now continues to work until reaches second sentinel (works correctly).
/*
* A simple program to sort numbers in the correct order
*/
#include <stdio.h>
#define MAX 10 //max elements in array
#define SENTINEL -999 //indicate the end of valid input
int main () {
// read values from stdin into array up to 'max' values
int tableFill(int a[], int max);
//compare two arrays and returns the first subscript they differ
int tableDiff (const int a[], const int b[], int n, int m);
//print all elements in array
void tablePrint (const int a[], int n);
int a[MAX];
int b[MAX];
int m,n,index;
m = tableFill(a, MAX);
n = tableFill(b, MAX);
tablePrint(a,m);
tablePrint(b,n);
index = tableDiff(a,b,m,n);
if(index==-1)
printf("-1. Arrays are the same.");
else
printf ("\n The arrays differ at index '%d'.\n", index);
return 0;
}
// read values from stdin into array up to 'max' values
int tableFill(int a[], int max) {
int r; // input from scanf
int next; // next input value
int cnt = 0; // count of values read
int *ptr = a; //pointer
printf("Enter the numbers! \n");
while ((r=scanf("%i", &next))==0 || (next != SENTINEL))
{
if (r == 0) //invalid input data
{
printf("Nonnumeric data entered. Please enter a number. \n");
while (getchar()!= '\n'); // flush invalid data
}
else if (cnt == max) //another value was read but the array is full
printf("Error - too many values. Array size %i.\n", max);
else {
*ptr++ = next;
++cnt;
}
}
return ptr-a; //(ptrb - b) should return the same value
}
//compare two arrays and returns the first subscript they differ
int tableDiff (const int a[], const int b[], int n, int m)
{
const int *ptra = a; //start for 1st array
const int *ptrb = b; //start for 2nd array
const int *endptra = a+m; //end for 1st array
const int *endptrb = b+n; //end for 2nd array
while(ptra<endptra && ptrb<endptrb && *ptra==*ptrb)
{
ptra++;
ptrb++;
}
if( ptra==endptra && ptrb==endptrb)
{
return -1;
}
else
return ptra -a; //(ptrb - b) should return the same value
}
//print all elements in array
void tablePrint (const int a[], int n)
{
int i; //loop counter
for (i = 0; i < n; i++)
printf ("%d ", a[i]);
printf ("\n");
}
You have a number of issues in your logic. The first of which in
while ((r=scanf("%i", &next)) == 1 && next != SENTINEL)
prevents the remainder of the code within the loop from ever executing in the event a non-numeric value is entered. If r != 1, you exit the loop, not process further within it.
While not an error, function prototypes within main only works when the functions exclusively do not rely on each other. They know nothing about one another during execution. Better to move the prototypes above main.
The remainder of your logic was somewhat difficult to follow and overly complicated. When you are looking for a difference within two arrays, you only need iterate over common elements. If they have differing number of elements, you know they differ by definition starting at the first unique element. So you can whittle down your comparison code quite a bit. Something like the following is fine:
/* check if array 'a' and 'b' are the same, else return index
* of first difference, otherwise return -1 for equal arrays.
*/
int tablediff (const int *a, const int *b, int sza, int szb)
{
int i, lim = sza < szb ? sza : szb; /* limit search to common elements */
for (i = 0; i < lim; i++) /* for each common element check */
if (a[i] != b[i])
return i;
if (sza != szb) /* if size differs, arrays differ */
return lim;
return -1; /* otherwise equal */
}
You can avoid the use of a SENTINEL just by proper bounds checking. Further, while you are free to create a arrayprint function that prints 2 arrays, it is far better to create a function that prints a single array and call it twice.
Putting those pieces together, and noting you do not use anything from stdlib.h, you could do something similar to the following:
#include <stdio.h>
#define MAX 10 //max elements in array
int tablefill(int *a, int max);
int tablediff (const int *a, const int *b, int sza, int szb);
void tableprn (const int *a, int sza);
int main (void) {
int a[MAX];
int b[MAX];
int idx, sza, szb;
sza = tablefill (a, MAX);
szb = tablefill (b, MAX);
tableprn (a, sza);
tableprn (b, szb);
if ((idx = tablediff (a, b, sza, szb)) == -1)
printf ("\n the arrays are the same.\n\n");
else
printf ("\n the arrays differ at index '%d'\n\n", idx);
return 0;
}
/* read values from stdin into array up to 'max' values */
int tablefill (int *a, int max)
{
int idx = 0, tmp;
while (idx < max && scanf (" %d", &tmp) == 1)
a[idx++] = tmp;
return idx;
}
/* check if array 'a' and 'b' are the same, else return index
* of first difference, otherwise return -1 for equal arrays.
*/
int tablediff (const int *a, const int *b, int sza, int szb)
{
int i, lim = sza < szb ? sza : szb;
for (i = 0; i < lim; i++)
if (a[i] != b[i])
return i;
if (sza != szb)
return lim;
return -1;
}
/* print all elements in array. */
void tableprn (const int *a, int sz)
{
int i; //varriable to print
for (i = 0; i < sz; i++)
printf (" %d", a[i]);
printf ("\n");
}
Example Equal
$ /bin/arraycmp <../dat/20intsame.txt
8572 -2213 6434 16330 3034 12346 4855 16985 11250 1495
8572 -2213 6434 16330 3034 12346 4855 16985 11250 1495
the arrays are the same.
Example Differ
$ ./bin/arraycmp <../dat/20intdif.txt
8572 -2213 6434 16330 3034 12346 4855 16985 11250 1495
8572 -2213 6434 16330 3034 12346 4855 16985 11250 1494
the arrays differ at index '9'
Providing Prompts for Input
When taking user input, it is a good idea to proving meaningful prompts as well so the user isn't left looking at a blinking cursor wondering if the program has hung, or what is going on. So in addition to the logic above, you would want to add simple prompting that explains what the program needs and how to provide the input. Something simple will do:
printf ("\nenter a max of 10 integers below 'ctrl+d` to end.\n");
sza = tablefill (a, MAX);
printf ("enter a max of 10 integers below 'ctrl+d` to end.\n");
szb = tablefill (b, MAX);
printf ("\nthe arrays entered are:\n\n");
tableprn (a, sza);
tableprn (b, szb);
(note: to generate a manual EOF on windoze, the key combination is ctrl+z)
So for entering less than 10 integers for each array you could do something like:
$ ./bin/arraycmp
enter a max of 10 integers below 'ctrl+d` to end.
10 12 14 16 17
enter a max of 10 integers below 'ctrl+d` to end.
10 12 14 15 17
the arrays entered are:
10 12 14 16 17
10 12 14 15 17
the arrays differ at index '3'
Look over the example and let me know if you have any additional questions.

passing array to function in c

can someone please help me figure out what i'm doing wrong here? i'm getting inaccurate results here. I seem to be getting the first value in the array each time and i cant seem to figure out what i'm doing incorrectly
#include <stdio.h>
int getbillsum ( int price[] );
int main( void )
{
int itemprice [10];
int total = 0;
for (int c=0;c <10;c++ ) //Looping to get item prices
{
printf ("\nEnter the price of the item: ");
scanf (" %d", &itemprice[c]);
}
total = getbillsum (itemprice);
printf ("%d", total);
return 0;
}
int getbillsum (int price []) //function to sum the values in array
{
int sum = 0;
for (int i=0; i<sizeof(price); i++)
{
sum+=price[i];
}
return sum;
}
You can't pass arrays to functions in C (well, not as an array anyway). Arrays decay into pointers, the sizeof which is always the same (4 for 32 bit systems, 8 for 64 bits).
For more information see paragraph 2.3 here.
The easiest, most common and most reliable way of solving your issue is to pass the length of the array as a second argument:
int getbillsum (int *price, size_t len)
{
int sum = 0;
for (int i=0; i<len; ++i)
sum += price[i];
return sum;
}
//usage
int main ( void )
{
int price[10];
for(int i=0;i<10;++i)
scanf(" %d", &price[i]);
printf("Sum: %d\n", getbillsum(price, sizeof(price)/sizeof(*price)));
return 0;
}
You also had a problem in your code: you added the return statement inside of your loop.
Just a quick-tip: The sum of an array of ints is not unlikely to be too much for a single int to hold, so I'd change the return-type of getbillsum to long, too
I've also edited your question, addressing quite a lot of issues considering how short your code was:
int getbillsum ( price );//missing type, changed to
int getbillsum ( int price[] );//better would be int getbillsum ( int *price ); but considering your question, left it as array
scanf ("%d", &itemprice[c]);//unsafe, changed it to
scanf (" %d", &itemprice[c]);//add space
total = getbillsum (itemprice,9);//why the second param?
total = getbillsum (itemprice);//to match function prototype
return sum;//moved OUTSIDE of the loop...
sizeof(price) does not give you the length of the array, but the size of the pointer (int price[]), which is probably 4. Also, you immediately return in the first for run. Put return outside the for loop.
You do fix it by supplying the array size, but you never use it. Update your getbillsum function:
int getbillsum (int price [], int length) //function to sum the values in array
{
int sum = 0;
for (int i=0; i<length; i++)
{
sum+=price[i];
}
return sum;
}
In addition to posted answers, you can consider a technique suggested in this answer.
Edit Quoted from comment
it's non-standard, dangerous (think of overflow, forgetting to
dereference at the correct offset and the like), and you should not
try this
In your case it will be something like that :
void *p = calloc(sizeof(itemprice) + sizeof(unsigned long int),1));
*((unsigned long int*)p) = 10;
quote from linked answer
n is now stored at ((unsigned long int)p)
Your getbillsum will look like that now (did not compile it, consider it as pseudocode)
int getbillsum (void* p)
{
int* price = p+sizeof(unsigned long int);
unsigned long int size = *p;
int sum = 0;
for (int i=0; i<size; i++)
{
sum+=price[i];
}
return sum;
}

factorial giving wrong answer

#include<stdio.h>
int max = 100;
int main()
{
int a,j;
int * arr = (int*)malloc(sizeof(int)*max);
arr[max-1] = 1;
scanf("%d",&a);
factor( arr, a);
display(arr);
}
int factor( int arr[],int a)
{
if (!a) return;
int i,carry;
for(i=max-1;i>=0;i--)
{
arr[i] = (arr[i]*a) + carry;
carry = arr[i]/10;
arr[i] = arr[i]%10;
}
factor( arr, a-1);
}
int display(int arr[])
{
int i;
for ( i=0; i<max; i++)
{
printf("%d",arr[i]);
}
}
HI this is my program to find the factorial of numbers but its giving wrong answer i dont know why ...???
like when i give input as 13
then according to myprogram 13 is to be treated in array as 1 and 3 but its giving random numbers -1216731443 -121673144 . i think malloc is having problem , but i can't identify it .
thank you
I think the reason why you are getting "random" numbers is because you haven't initialized the carry variable. In the for loop, you are adding the un-initialized value of carry to the array which will cause undefined results.

Resources