-2
void main() {

    int arr[] = {1,2,3}

}

void main(int* a,int n) {

   for(int i=0; i<n;i++)

     a++;

int size = (a-(&a[0]))/4;.   //calculate size of array?

}

If for example the first array element is in address 4, after the loop the arr pointer will point to address 16, can I calculate the size of the array doing (16-4)/4, by casting int or somehow? Thanks.

I tried the part of the code above.

Gerhardh
  • 11,688
  • 4
  • 17
  • 39
Mark Y
  • 1
  • 2
    Please activate your compiler (and ide) warnings, this will save you (and us) a lot of time – Ôrel Feb 27 '23 at 11:22
  • Yes, you can do arithmetic on "addresses": C calls this *pointer arithmetic*, and it is a vital part of the language. But it is not something you are going to learn properly by making guesses and then asking questions about. Please read the section(s) on "pointers" and/or "arrays and pointers" in your favorite C tutorial. (If you don't have a favorite, you might start [here](https://www.eskimo.com/~scs/cclass/notes/sx10b.html).) – Steve Summit Feb 27 '23 at 11:34
  • As I understand, you want to know how to find the size of an array. There is a Q/A about that here: https://stackoverflow.com/questions/37538/how-do-i-determine-the-size-of-my-array-in-c – nielsen Feb 27 '23 at 12:07

1 Answers1

0

I would start with the correct definition of the main function and the correct size type. You can have only one definition of the function in the whole programme.

void foo(int *a, size_t n) 
{
    int *saved = a;
    for(size_t  i=0; i<n;i++)
        a++;
    size_t size = a - saved;
    printf("%zu\n", size);
}

int main(void)
{
    int arr[5];

    foo(arr, sizeof(arr) / sizeof(arr[0]));
}
  1. It can't be done your way as a[0] after incrementation does not reference the original start of the array. You need to save it.
  2. You do not need to divide by the size of int as pointer arithmetic is done in the type units (in this case int's) no bytes or chars
0___________
  • 60,014
  • 4
  • 34
  • 74