I am pretty new to C programming. I am trying to program a lookup function to match a RFID tag to a table of valid tag numbers (a multi-dimensional array).
My displays would indicate that a typed-in code should match an entry in the array, the program does not display "Matched" within the strcmp for/next loop. (see output results below)
AWOL,
Is there a way to determine the number of bytes in the table.
When I use sizeof(tags) I get 10 - the length of the first entry (not sure why I don't get 11 since sizeof(code) returns 11)
sizeof(tags) gives you 10 because that's the length of the tags array,
in bytes. Each array element is a pointer to a char, thus two bytes.
You have 5 elements in the array so... 5*2 => 10.
Your RFID codes are "technically" not part of the array, they're just
chunks of initialized memory pointed to by an array element of tags[].
If you want to count how many bytes are in all of your codes, you'd
have to do something like this:
int sum = 0;
for (int i=0; i<sizeof(tags)/sizeof(tags[1]); i++) {
sum += strlen(tags[i]);
}
Alas, this won't count the NULs at the end of each string.
The expression
sizeof(tags)/sizeof(tags[1])
give you the number of elements in your tags[] array.
Of course sizeof(tags)/sizeof(tags[1]) only works because all entries are the same length.
tags is an array of pointers. tags[1] is a pointer. The expression doesn't depend at all on the data that the pointers point to. If you were to change the lengths of the strings, it would still yield the same result.
The expression doesn't depend at all on the data that the pointers point to. If you were to change the lengths of the strings, it would still yield the same result.
I think AWOL was concidering the possibility that the tags end up being just a single string, thus tags[1] will be 'wrong'.
But I think that any index will yield the same result, although it is not 'good practice'.
[edit]I assumed you where replying to AWOL, but you where not.
/me miss quote.[/edit]
But I think that any index will yield the same result, although it is not 'good practice'.
Yeah, that's right. Funny, isn't it? You can use sizeof(tags[0xF3333]) and that will work just as well. The array element is never dereferenced in a sizeof expression.
And did you know that wherever you use the expression tags[0], you can also write it as 0[tags]? That's not the best practice either.
Originally, I was going to use sizeof(tags)/sizeof(char *) but thought that might blow away a noob or two.
Actually, that sorta thing might be better if the array elements were a
user-defined type, as defined with #typedef.
Why I used [1] instead of [0]? Got me. Musta been those mental blocks
my folks gave me for Christmas one year.