0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


static int a1(int *a)
{
    int middleItem;
    int midIndex;
    if (a == NULL || sizeof(a) % 2 == 0)
        return 0;
    midIndex = sizeof(a) / 2 ;
    middleItem = a[midIndex];
    for (int i=0; i<sizeof(a); i++)
        {
            if (i != midIndex && middleItem >= a[i])
            return 0;
        }
        return 1;
 }

int main()
{
    int a[] = {9};
    for (int i=0; i<sizeof(a); i++)
    {
        a1(a[i]);
    }
    return 0;
}

An array with an odd number of elements is said to be centered if all elements (except the middle one) are strictly greater than the value of the middle element. Note that only arrays with an odd number of elements have a middle element.

output:

returns 1 if it is a centered array, otherwise, it returns 0.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

1 Answers1

2
  • sizeof(a) is number of bytes in a and it is not necessarily same as the number of elements in the array a.
  • It is even worse in the function a1: now sizeof(a) is the size of pointer and you cannot get number of elements from that, so you have to pass it separately.
  • Passing a[i] as the first argument of a1 is wrong because a[i] is an integer while a pointer is required for the argument.
  • You will want to output what the function returned.

Try this:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


static int a1(int *a, int size)
{
    int middleItem;
    int midIndex;
    if (a == NULL || size % 2 == 0)
        return 0;
    midIndex = size / 2 ;
    middleItem = a[midIndex];
    for (int i=0; i<size; i++)
        {
            if (i != midIndex && middleItem >= a[i])
            return 0;
        }
        return 1;
 }

int main()
{
    int a[] = {9};
    int size = sizeof(a) / sizeof(*a);
    printf("%d\n", a1(a, size));
    return 0;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
MikeCAT
  • 73,922
  • 11
  • 45
  • 70