I am working on a C program that deals with sets, and I am having trouble getting the values for an array in my C program. I am thinking that there is a logical error in the function below.
sizeA is 26, and setA is a boolean set of size 26.
Here is how the function should turn out if sizeA is 5:
Enter the first element in Set A: //user enters h
Enter the next element of Set A: //user enters i
Enter the next element of Set A: //user enters j
Enter the next element of Set A: //user enters k
Enter the next element of Set A: //user enters l
fffffftttttffffffffffffff
However it turns out like this if sizeA is 5:
Enter the first element in Set A: //user enters h
Enter the next element of Set A: //user enters i
Enter the next element of Set A: //user enters j
Enter the next element of Set A: //user enters k
Enter the next element of Set A: //user enters l
ffffff
I would like to know how to fix this problem.
Here is the code:
void getSetA(bool setA[], int sizeA)
{
letters element, letter;
int position = 0, num, i;
for(i = 0; i < sizeA; i++) //sizeA is inputted before
{
setA[i] = FALSE;
}
printf("\nEnter the first element in Set A: ");
element = getcharNoBreaks();
if (element >= 'a' && element <= 'z')
{
setA[element-'a'] = TRUE;
}
for(num = 1; num < sizeA; num++)
{
printf("\nEnter next element of Set A: ");
element = getcharNoBreaks();
if(element >= 'a' && element <= 'z')
{
setA[element - 'a'] = TRUE;
}
else printf("Element out of range");
}
printf("\n");
for(i = 0; i < sizeA; i++)
{
if(setA[i] == TRUE) printf("t");
else printf("f");
}
}
Note that letters, is a type I have defined (as all the letters of the alphabet), and getcharNoBreaks() is a function that is equivalent to getchar().
Thank you :)
puts("fffffftttttffffffffffffff")setA(I presume) is an array of only 5 elements, but indexing with'l' - 'a'is index 11, which is clearly out of bounds.h,i,j,k,l, the true flag will be set for those letters