Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know the end of int* array?

Tags:

arrays

c

int

I'm making a dynamic array with int* data type using malloc(). But the problems is, how to know end of array?

There no an equivalent to \0 for int* data type,so, how to do this? Pass size as out parameter of function?

like image 355
Jack Avatar asked Apr 19 '12 00:04

Jack


People also ask

How do you find the end of an array?

C arrays don't have an end marker. It is your responsibility as the programmer to keep track of the allocated size of the array to make sure you don't try to access element outside the allocated size. If you do access an element outside the allocated size, the result is undefined behaviour.

What does int * array mean?

It's an array of pointers to an integer. ( array size is 9 elements. Indexes: 0 - 8) This can also be stated as being an array of integer pointers. int array[9] , is an array of integers.

Is int * the same as array?

The difference is when you do int array[100] , a memory block of 100 * sizeof(int) is allocated on the stack, but when you do int *array , you need to dynamically allocate memory (with malloc function for example) to use the array variable. Dynamically allocated memory is on the heap, not stack.

How do you find the length of an int array?

To determine the size of your array in bytes, you can use the sizeof operator: int a[17]; size_t n = sizeof(a); On my computer, ints are 4 bytes long, so n is 68. To determine the number of elements in the array, we can divide the total size of the array by the size of the array element.


1 Answers

C doesn't manage array lengths, as some other languages do.

you might consider a structure for this:

typedef struct t_thing {
  int* things;
  size_t count;
} t_thing;

in use:

t_thing t = { (int*)malloc(sizeof(int) * n), n };
like image 162
justin Avatar answered Oct 11 '22 11:10

justin