user1020710
user1020710

Reputation:

suggestion for end of integer array marker

I've an array of fixed size in C. There I might have any number (less than the array size) of useful element. Now I need only my useful element. So I'm thinking of using an end of array marker for integer array. First of all


a) Is this possible?

b) If possible, How?

Upvotes: 0

Views: 1494

Answers (6)

qwertz
qwertz

Reputation: 14792

There are a two ways to do that (if the int value could have any possible value for int).


First option: Storing the count of elements in your array, and increase the value if you add/remove items.

int count;
int *array;

Second option: Making a structure with the pointer to the next variable in the array. If its NULL you have reached the end of your list.

struct Item {
    int i;
    struct Item *next;
}
// pointing at the start adress:
struct Item *start = NULL;
// adding first item:
start = malloc(sizeof(struct Item));
start->i = 123;
start->next = NULL // mark the current end of list (not needed if you add a value right after the first)
// adding second item:
start->next = malloc(sizeof(struct Item));
start->next->i = 456;
start->next->next = NULL
// etc

Upvotes: 0

Mihir Mehta
Mihir Mehta

Reputation: 13843

Logically it is possible if you can find unique integer number that can act as END_OF_ARRAY , and will not be there in your set of useful number ...

you just need to to add it explicitly at end ... and check for number later that will indicate end

Upvotes: 3

SpacedMonkey
SpacedMonkey

Reputation: 2773

It depends what it is an array of and what values are valid.

You say you have an array of int, use any value that is not valid for the list. If all entries are positive, use a negative number for the end. If the values are all under INT_MAX, use that as the end marker.

Upvotes: 2

Nim
Nim

Reputation: 33645

I would take a slightly different approach

struct IntArray
{
  int data[N];
  int size; // <-- use this to keep track of the size.
}

Upvotes: 3

High Performance Mark
High Performance Mark

Reputation: 78344

Yes, create an integer variable called end_of_array_marker.

Does it need to be more complicated than this ?

Upvotes: 0

Adam Sznajder
Adam Sznajder

Reputation: 9216

You can always treat your array as an buffer and keep track of current number of useful elements.

struct buffer 
{ 
     int* array;
     size_t size;
}

Upvotes: 1

Related Questions