This is probably going to be a pretty basic question but I’m confused on how to implement something like this.
For a class I’m taking on C I need to take two arrays that can vary in length and compare their elements in a separate function. (This function only takes the arrays as parameters, not their sizes) Any element that is in both arrays I need to put into another array and return that array (NOTE: each array is like a set in that no elements repeat in the same array). I have looked into how I would implement this a little bit and here are some of the issues I’m running into.
-
How do I know where the end of the array is?
I think I saw that I might be able to do {0} as an element in the array for a null element. If this is true I don’t know what I would compare this element to in order to check for null.
-
I think I’m supposed to pass pointers to the first element of the array because I don’t think C will let the values of an array be passed, but a little unsure.
If I do pass the arrays as pointers, how can I access the arrays elements to get their data?
-
When returning the array to the main function, how can I return the resulting function without the memory being cleared up?
Should I make the resulting array global, or is there a better way of handling it?
Thanks in advance.
Your question is a bit vague. It looks like you want to implement set intersection where you have two sets, represented by arrays, and the output is another array implemented as an array.
1. How do I know where the end of the array is?
In C, there is no way to tell. If you cannot pass the length as a function then you will not be able to do a robust solution. It will need to be something similar to #2.
2. I think I saw that I might be able to do {0} as an element in the
array for a null element. If this is true I don’t know what I would
compare this element to in order to check for null.
You can add a null character, which is just the value 0. To check, you will need to compare to 0. I do not know what do each of your array elements consist of, but one thing to watch of for is that none of those value is allowed to be zero anymore since it is reserved as an end of array marker.
3. I think I’m supposed to pass pointers to the first element of the
array because I don’t think C will let the values of an array be
passed, but a little unsure.
Yes. You will pass the pointed to first element, which in C is the array symbol.
4. If I do pass the arrays as pointers, how can I access the arrays
elements to get their data?
Say you passed pointer A, you can access the elements by simple indexing as A[i], to grab the element i.
5. When returning the array to the main function, how can I return the resulting function without the memory being cleared up?
In the function you are writing, you can
mallocan array and pass a pointer to the array created by malloc. Malloce’d memory is not deleted when the function exits.