PDA

View Full Version : testing the existance of array element (in C)


MattyJim
01-07-2007, 04:56 PM
Hello there!


Is there a way to test the existance of the last element in an array using the C language?

Every time I try this, by looping through an array until the code goes out of bounds, I end up causing an error that I don't seem to be able to handle properly (I'm using <errno.h>, by the way).


Using something like.......

if (errno != 0)
{
break;
}

.......for example.



Anybody know how this should be done properly?

MattyJim
01-07-2007, 05:17 PM
no problem, chums!


found this on an earlier post from 'obiwanjabroni':

char foo[50];
int arraySize = sizeof(foo)/sizeof(char);



that should do the trick!! :)

rpgfan3233
01-10-2007, 05:04 AM
Even better is

char foo[50];
int arraySize = sizeof(foo) / sizeof(*foo); // sizeof(*foo) is like saying sizeof(foo[0])


That way works for an array of any type, whether it is char, int, double, etc. The reason why it works is because you are telling the compiler to take the size of the entire array and divide it by the size of one array element. That will give you the number of array elements.

MattyJim
01-19-2007, 11:46 PM
yeah, i see what you mean.

thanks for your help! :)

Curtis D
01-24-2007, 05:52 AM
If you know you are dealing with a string, using the strlen function (located in string.h) will give you the amount of chars, not including the string terminating null byte.

rpgfan3233, quite an elegant solution! :thumbsup:

rpgfan3233
01-24-2007, 08:45 AM
Great solution, but one thing to keep in mind is that it is NOT for dynamically allocated memory, which are commonly used for strings, among other things:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (void) {
// max string length in characters
size_t MAX_STR_LEN = 255;

// dynamically allocate space to store a string of MAX_STR_LEN bytes
char* my_string = (char*)malloc(sizeof(char) * MAX_STR_LEN + 1);

// initialize the string with null terminators
memset(my_string, 0, MAX_STR_LEN + 1);

// read a string from STDIN to store for testing purposes
printf("Enter your name: ");
scanf("%s", my_string);

// ensure string is null-terminated
my_string[MAX_STR_LEN] = 0;

// doesn't work properly
for (int i = 0; i < sizeof(my_string) / sizeof(*my_string); i++)
printf("%c", *(my_string + i));
printf("\n");

// this works properly, assuming my_string is null-terminated, which we ensured earlier
for (int i = 0; i < strlen(my_string); i++)
printf("%c", *(my_string + i));
printf("\n");

// works the same way as using strlen(), sort of
for (int i = 0; (i < MAX_STR_LEN) && (*(my_string + i) != 0); i++)
printf("%c", *(my_string + i));
printf("\n");

return 0;
}