0
#include<stdio.h>
int main()
{
    setbuf(stdout,NULL);
    int a[],i,lim,sum=0;
    printf("Enter the limit of the array: ");
    scanf("%d",&lim);
    printf("Enter the values: ");
    for(i=0;i<lim;i++)
    {
        scanf("%d",&a[i]);
    }
    int *p;
    for(p=&a[0];p<lim;p++)
    {
        sum=sum+*p;
    }
    printf("Sum= %d",sum);
    return 0;
}

While running the code I'm getting the following error
..\src\Test6.c: In function 'main':
..\src\Test6.c:5:6: error: array size missing in 'a'
..\src\Test6.c:14:15: warning: comparison between pointer and integer

Please help me understand why I've to declare the array size when I have no issues doing the same without pointers.
Or please help me understand what change should I make to rectify the error:)

Althaf
  • 29
  • 6
  • arrays are not pointers, pointers are not arrays. You might like to read section 6 of the [comp.lang.c faq](http://c-faq.com/). – pmg Jul 17 '20 at 08:19
  • What do you mean by " I have no issues doing the same without pointers"? You always need to declare the array size, regardless of whether you later use pointers. – interjay Jul 17 '20 at 08:23
  • Closed this as a dup. The accepted answer gives a deep explanation on the difference between arrays and pointers. – klutt Jul 17 '20 at 08:24
  • You could really use your warning and errors. When declaring arrays, you must specify its size or you could use `VLAs` if your compiler supports `c99 or c11` or use a dynamic array. Then for the second warning, read the comment by @PaulOgilvie – Shubham Jul 17 '20 at 08:32

2 Answers2

0

declare the size too when declaring the array.

eg.

int a[100000];

here you can put atmost 100000 elements in the array.

ZBay
  • 352
  • 1
  • 6
  • 17
0

your loop

   for(p=&a[0];p<lim;p++)
   {
       sum=sum+*p;
   }

should be written as

for (p = &a[0]; p < &a[lim]; p++)
{
    sum += *p;
}

or, more usually using index,

for (int index = 0; index < limit; index++)
{
    sum += a[index];
}
pmg
  • 106,608
  • 13
  • 126
  • 198