-
How to do array subsets?
Is there an easy way to do subsets of arrays? The whole way that C does arrays makes me think that there probably is.
Note that it doesn't really matter whether I get an array out or the concatenated data; in fact, a way to do both would be awesome.
-
If you have an array that you want to have a subset of, then you can do this:
Code:
int bigArray[1000];
...
int *subsetArray;
size_t subsetSize
...
subsetArray = &bigArray[someIndex]
subsetSize = 100;
...
--
Mats
-
Umm... sorry, but I'm a bit of a n00b when it comes to C. What am I supposed to do with this new size_t variable?
-
A subset of an array is obviously not necessarily "the rest of the array", so you need a size of it. How else would you know how many elements there is in your subset? [Arrays don't have "endmarkers" like strings]. You'd need to pass the size to the function using the subset.
I used size_t because that is the correct type to be used for sizes [it's an unsigned integer that is guaranteed to cover the memory range that a pointer could range through]. If size_t is confusing, think of it as unsigned int.
--
Mats
-
Oh, hang on, I think you might have misunderstood my question. I'm not passing this to a function. What I have is a byte array from an NSData object (Apple's preferred method of handling binary data). It's a MIDI file, so I want to check that the first four bytes are "MThd". And I'd really love to not have to use an insanely complex expression to find this out, since I'm going to have to do this sort of thing a lot.
However, now that I think about it, I don't think it's even possible to do comparisons of arrays in C. So, I might have to think of a different way to tackle this.
-
Why not just make a string by reading 4 bytes into a char array of 5 elements, set the fifth element to zero, and use strcmp?
Or read 4 bytes into a char array and use:
Code:
if (arr[0] == "M" && arr[1] == "T" && arr[2] == "h" && arr[3] == "d") ...
else ...
It's not terribly complex.
--
Mats