Length of array using pointer

Started by
5 comments, last by Zahlman 16 years, 8 months ago
Hi! Everyone, int *array; Suppose, I've initialized it in somewhere. Now, how do I know the length of the array using this pointer? int getLength() { return ..... what? } Thanks in advance.
Advertisement
You can't.
You can either inject a terminator character in that array, and check for it or store the length in a variable.
Maybe you can create a struct with an int to indicate the length:

struct intArray{int* dataint length;};

Look at all the pretty colours!
To expand on the above suggestion to keep the length around yourself, your main alternatives are, in C++, to use a container (std::vector offers all the storage benefits of raw memory buffers, without the disadvantages), and in C to keep the size of the object around (this generally forces you to implement the array bookkeeping for every type).

A generic but type-unsafe system would be:

typedef struct {   size_t size;  void * data;};


A generic type-safe template-like system could look like:

#define ARRAY(T) struct { T *data; size_t size; }#define ALLOC_ARRAY(a,size) do { \   a.data = malloc( size * sizeof(*a.data) ); \   a.size = size; } while(0)#define RESIZE_ARRAY(a,size) do { \   a.data = realloc( a.data, size * sizeof(*a.data) ); \   a.size = size; } while(0)#define FREE_ARRAY(a,size) do { \   free(a.data); a.data = 0; } while(0)#define VALID_ARRAY(a) (a.data != 0)#define ARRAY_GET(a,i) (a.data)#define ARRAY_SET(a,i,x) do { \   a.data = (x); } while(0)


WIth the obvious "macros are evil" restriction that a should always be an array variable and not an expression.
As Fase said, you can't so you have to keep the length around. If this is C++, it would be more convenient to use std::vector which is a fancy array and does remember it's length.
There are compiler dependent methods for determining the size of a dynamically allocated array. For instance on MSVC, you can use _msize() on a pointer to determine how many bytes were allocated on that pointer.

Previous thread on this topic.
Quote:Original post by moo_gamer
Hi! Everyone,

int *array;

Suppose, I've initialized it in somewhere.

Now, how do I know the length of the array using this pointer?

int getLength() {

return ..... what?

}

Thanks in advance.


you can't, and it's not good practise. You must keep the length somewhere.
I suggest you use some sort of container (Like a Linked List or a Vector or some sort of ArrayList, etc..)
Just to clarify:

Quote:Original post by SiCrane
There are compiler dependent methods, for some compilers/platforms, for determining the size of a dynamically allocated array.


Quote:Original post by memento_mori
you can't portably, and it's not good practise. ...the length must be kept somewhere.

This topic is closed to new replies.

Advertisement