Kamil Kamil
Kamil Kamil

Reputation: 15

the defined variable is different

why is the variable in the average function is different from the same variable in the main function? I do not know how to solve it because I'm just learning.

#include <stdio.h>
#define  SIZE (sizeof(number)/sizeof(int))

int number[] = {5,65,84,25,644,2};

int average(int *number)
{
    printf("size = %ld\n",SIZE);
    int sum=0;
    for(int i=0;i<=SIZE ;i++)
    {
    sum += number[i];
    }
    return sum/SIZE;
}

int main()
{
printf("average : %d\n",average(number));
printf("number of elements: %ld\n", SIZE);


return 0;
}

Upvotes: 1

Views: 38

Answers (3)

scipsycho
scipsycho

Reputation: 587

You have defined a global variable number which is an array.

In the function average , you defined another variable with the same name/identifier number (although of different type i.e. a pointer).

Now, when you use number inside the main function you are actually using the pointer number and not the global variable number. This is also known as variable hiding.

If you want to use the global variable change the name of the argument of the average function to something else or you can go the hard way and do something like this.

Happy Coding;)

Upvotes: 0

Stephan Lechner
Stephan Lechner

Reputation: 35164

You use a macro (i.e. #define ...) to specify SIZE. The macro is expanded "textually" wherever you make use of it, and it is interpreted in the respective context, i.e. it's meaning depends on where you place it.

So in main, number as part of your macro refers to the global variable number, whereas in the context of function average, it refers to the function argument number (which hides the equally named global variable).

Anyway, it's impossible to deduce any array size from a pointer variable. You'll have to pass the number of elements as an extra argument.

Upvotes: 1

dbush
dbush

Reputation: 225477

Within main, number is a global variable which is an array. So sizeof(number) gives you the size of the whole array in bytes.

In the average function however, number is a parameter to the function and has type int *. So sizeof(number) in that case gives you the size of the pointer, not the size of the array.

Either don't pass a parameter and just use the global, or pass the size of the array as a separate parameter to the function.

Upvotes: 0

Related Questions