Search code examples
c

passing argument 2 makes pointer from integer without a cast


I have this function:

int second(int x,int c[100])
{
    int b,e=0;
    for(b=0;b<x;b++)
        {
        if(c[b]!=(65||117))
        e++;
        }
        return (e);
}  

this loop will check how many numbers in an array are not equal
to 65 or 117 and the value to be incremented is meant to calculate how many
numbers are those and this value will be returned to the main function.

Now I want to use the returned value in the main function. Here is the syntax I am using:

h=second(x,c[100]);

I am getting this error:

"passing argument 2 of second makes pointer from integer without a cast"

How do make the function return that value?


Solution

  • To understand what is happening, one needs to understand the following things.

    In int second(int x,int c[100]), the declaration of parameter c as an array of 100 int is automatically adjusted to declare c as a pointer to an int. This special handling of arrays is always applied to function parameters. (It is not applied to subparts of parameters. E.g., a pointer to an array is not converted to a pointer to a pointer.)

    Somewhere later in your program, you probably have a line like int c[100];. That line does declare c to be an array of 100 int.

    In h=second(x,c[100]);, the expression c[100] refers to element 100 of the array c. Thus, this expression is a single int. You should not pass an int to the function because it is expecting a pointer to int. You probably want to pass a pointer to the first element of the array. The C syntax for this is &c[0]. C provides some assistance to let you abbreviate this as c. If you write h = second(x, c); then c will be automatically converted from an array to a pointer to its first element.

    This automatic conversion happens whenever an expression (including any subexpression) is an array and is not the operand of sizeof or of unary & and is not a string literal used to initialize an array.

    Additionally, if(c[b]!=(65||117)) does not test whether c[b] is not equal to 65 or 117. To perform this test, you should use if (c[b] != 65 && c[b] != 117). The way you wrote it, 65||117 is an expression meaning “true if either 65 or 117 is true”. For these purposes, non-zero values are true, so 65||117 is true. Also for these purposes, true becomes the integer 1 (and false would be 0). Thus, this test is if (c[b] != 1), which is not what you want.