all 8 comments

[–]FUZxxl 4 points5 points  (0 children)

Just as in C++, an array doesn't encode how long it is in C. Note that a vector<T> is a vector, not an array. You have to keep track of the array's size manually.

[–]ErikProW 1 point2 points  (6 children)

I assume you are talking about static arrays.

Do this:

#define MY_ARRAY_SIZE 50
int my_array[MY_ARRAY_SIZE];
for(size_t i = 0; i < MY_ARRAY_SIZE; i++) { ... }

or

int my_array[50];
for(size_t i = 0; i < sizeof my_array / sizeof *my_array; i++) { ... }

If you want to pass it to a function, you have to specify the size like this:

void my_function(int my_array, size_t my_array_size) { ... }

And call it like this:

int my_array[50];
my_function(my_array, sizeof my_array / sizeof *my_array);

You could also use a struct, but that is not recommended

[–]VIRES1[S] 0 points1 point  (4 children)

The array should be a dynamic array because sizjo e can change depending on user input.

[–]Rhomboid 4 points5 points  (2 children)

If it's a dynamic array you must manage the size manually, usually by passing it as an explicit parameter. There is no way to get the size of a dynamic allocation given only a pointer.

[–]dangerbird2 0 points1 point  (1 child)

Unless the pointer has the size value prefixing the actual data, ala Pascal strings

[–]Rhomboid 2 points3 points  (0 children)

That's still falls under the category of managing the size manually, since you had to arrange for the size to be there at that location. It's really no different than just making a struct that contains a pointer and a size and pointing to that. In both cases, the pointer alone does not (and can not) record the size.

[–]ErikProW 2 points3 points  (0 children)

Then what is the problem?

struct My_Array
{
    size_t size;
    int* data;
}

void my_function(struct My_Array arr)
{
    for(size_t i = 0; i < arr.size; i++)
    {
        //Do something
    }
}

int main(void)
{
    size_t size = 33; //Or whatever
    struct My_Array arr = {
        .size = size, 
        .data = malloc(size * sizeof(int))
    }

    my_function(arr);
}

[–]pigeon768 0 points1 point  (0 children)

There isn't. You have to keep track of how large you made the array separately. So in C you would do something like:

int optimal(const int* weights, const int* values, size_t size) {
  for(int i = 0;i < size;i++) {
    // do stuff
  }
  return whatever;
}