Concept: Adding and updating elements to a single array of structures
A conceptually problem I am having in doing this problem...
I have an array of structures like so:
Code:
[empty][empty][empty][...][empty]
Initially all spots are empty. I read an line and take from it an ID and an element. The ID is what will serve as the distinguishing agent among these spots in the array of structures.
Now, for the first read, I take the ID and element and assign it to the first spot.
Next, take the next ID and element and put it into the second spot IF this ID doesn't match the first ID. If the ID matches the first ID, I will put the element under the first spot. If not, it will take place in the first empty spot. This is the case and thats what happens.
The third read comes in, it is a different ID. I put it in spot 2 that has been empty along with its ID and the element that it came with.
Thus, the array becomes...
Code:
[ID #5 - element 1, element 2][ID #1 - element 1][empty][...][empty]
And so forth this will continue until all data has been read in.
SO, to make this code. I must keep track of the ID's I am reading in. Thus, somehow be able to read an ID in and to see if it matches a previous ID that has been read in. If it matches, then to just update/add to that spot where the ID already exists. IF it doesn't have an match, fill in the next empty spot.
My code design so far:
Code:
num_elements = 0; // A counter to count number of elements read in
array = calloc(1000, sizeof(data_type)); // Used calloc to initialize all array elements to 0
// Note the structure is called data_type
while(...) { // Read through till the end
flag = get_data(&id, &element) // Gets a single ID and an element.
// Rest of code focus on manipulating the array of structures...
++num_elements;
found_match = 0;
for(i = 0; i < num_elements; ++i) {
if(id == array[i].id) {
found_match = 1; // A match was found, update the array only!
/******************
* Update the
* Array at this spot
******************/
}
}
if(found_match != 1){ // A match wasn't found, add the ID to the array!
for(i = 0; i < num_elements; ++i) {
if(array[i].id = 0)
data[i].id = id;
data[i].element1 = element;
break;
// From my understanding, break will get us out of the current "for" loop and continue to
// the next statement
}
}
}
}
How does this plan sound?
Comments?