0
void test(int* x, int y) {
    for (int i = 0, j = 0; i < y; ++i) {
        if (i % 2 == 0) {
            x[j] = i;
            ++j;
        }
    }
}

int maxRange = 10;
int *a;
test(a, maxRange);
// a = { 0, 2, 4, 6, 8, 10 }

How can I find length of a?

The length is 6.

I tried sizeof(a) and sizeof(a) / sizeof(a[0]).

Thanks for any help!

Dominique
  • 16,450
  • 15
  • 56
  • 112

3 Answers3

2

This is one of the major problems working with arrays in C: no way to know the length of it, but there are ways to work around this:

  • Either you keep track of the amount of entries you put in the array (as already proposed by Sourav).
  • Either you start by putting default values into your array (like -1). If ever you need to know the length of the array, you just look for the index of the first -1 and if there isn't one, it means that your array has reached full length.
Dominique
  • 16,450
  • 15
  • 56
  • 112
1

You cannot get the length of the allocated memory to a pointer, from a pointer using sizeof operator. You need to keep track it yourself, and pass it around to any function call which may need it.

Related reading: Arrays are Pointers?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

How can I find length of a?

a is a pointer, not an array. It has not been assigned a value. a has a length in that a pointer take up so many bytes like 4 or 8, but a does not point to any length of memory for data, yet.

Instead, allocate memory:

int n = (maxRange + 1)/2;  // Number of `int` used by test().
a = calloc(n, sizeof *a);  // Allocate zero'd memory.
if (a) {
  test(a, maxRange);
  for (int i = 0; i < n, i++) printf(" %d", a[i]);
  free(a);
}

If code hopes to print 0 2 4 6 8 10, change allocation and test() loop condition

// int n = (maxRange + 1)/2;
int n = (maxRange + 2)/2;

// for (int i = 0, j = 0; i < y; ++i) {
for (int i = 0, j = 0; i <= y; ++i) {
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256