Bug While i try to compare - c

Actually i have a little bug with this code:
printf("Estadio Nemesio Diez\n\n");
for(i=0;i<12;i++)
{
if(ultimoAnoDiez[0]==ultimoAnoDiezOriginal[i]);
{
mes=i;
}
}
i am comparing 2 arrays, and im selecting the index[0], because that array is already sorted, but when i compile and execute the file, the program says that all the values on each array is the same, but if i print the values of each array all are diferents.
I will appreciate the help
BTW Im programmin on C

I think there can be two reasons:
First
your if condition is ending with ; (making {/* othet statement */} a block but not if block)
Second
(ultimoAnoDiez[0]==ultimoAnoDiezOriginal[i])
should be (you should be comparing individual values and not all values(i) to first value(0) only)
(ultimoAnoDiez[i]==ultimoAnoDiezOriginal[i]);
Further to check for array equality you return as soon as you find unequal values so it should be like
int mes = 12;
for(i=0;i<12;i++)
{
if(ultimoAnoDiez[i]!=ultimoAnoDiezOriginal[i])
{
mes=i;
break;
}
}
if(mes < 12){
//UNEqual
}

Related

Comparing elements from two 2d-arrays in C without strcmp

I am creating a spell-checker in C. I have a dictionary array which is a 2d array. So each word in the dictionary takes a row in the 2d array. In the same way, my input array is also a 2d array. I want to check the spelling of the rows/words in my input array. I cannot use strcmp
An example of input array
['boy','girll','.','friend',' ']-can contain spaces,punctuation and words. We only care about spelling words
if a punctuation/space is compared against a word,we ignore it and move onto the next word.
example of dictionary
['boy','girl','cow'...]-all are words
My code is:
for (int a = 0; a < MAX_INPUT_SIZE + 1; a++)
{
for (int b = 0; b < MAX_DICTIONARY_WORDS; b++)
{
if(tokens[a]==dict_token[b])
{
printf("correct");
}
else
{
printf("wrong");
}
}
}
The output is all "wrong". Though 5 out of the 6 word input should be correct.
Every test returns false because the comparison you're using,
if(tokens[a]==dict_token[b])
is comparing two pointers that are never going to point at the same address, because, the tokens you are testing are in a completely separate bit of memory to the dict_token dictionary that you are comparing them with.
You need to pass the two pointers tokens[a] and dict_token[b] to a comparison function that will perform a letter-by-letter comparison, and which will return one value when it finds a difference between them, and another when it gets to the end of both without finding a difference. In other words, you need to write an implementation of strcmp.

Sorting array of structures in C error

I am writing a phonebook application in C. I have an array (sort2) of structure Nodes (contacts). I am trying to sort the array by nodes->pnum (phone number); s is the number of nodes in array. For some reason, the loop creates an error after first iteration. Why?
for(i=0; i<s;i++)
{
for(j=0;j<s;j++)
{
num1= sort2[i];
num2= sort2[j];
if(num1->pnum<num2->pnum)
{
temp=sort2[j];
sort2[j]=sort2[j+1];
sort2[j+1]=temp;
printf("%s",sort2[j]->lname);
printf("%s",sort2[j+1]->lname);
}
}
}
You are accessing beyond the bounds of the array in the following lines when j is equal to s-1:
sort2[j]=sort2[j+1];
sort2[j+1]=temp;
printf("%s",sort2[j+1]->lname);
I think you meant to use:
sort2[j]=sort2[i];
sort2[i]=temp;
printf("%s",sort2[i]->lname);
In the above code when you refer to sort2[j+1] at the last iteration of the loop it would result into access to the garbage memory as array indexing starts from 0 so the last index is limit-1 i.e s-1 in this case but code will access sort[s]. Thus this would result into abnormal termination of the program in certain cases.
And starting the inner loop from the next value of outer loop counter would save some iterations of your code.
so try
for(i=0; i<s;i++)
{
for(j=(i+1);j<(s-1);j++)
{
num1= sort2[i];
num2= sort2[j];
if(num1->pnum<num2->pnum)
{
temp=sort2[j];
sort2[j]=sort2[j+1];
sort2[j+1]=temp;
printf("%s",sort2[j]->lname);
printf("%s",sort2[j+1]->lname);
}
}
}

Test for first empty value of array

Is there anyway to test for the first empty value of a 2 dimensional int array in c?
In my current program, I used 2 for loops before the main program(while loop) to set all the values of my 2 dimensional array to -9999. Then inside my main while loop, I test for the first -9999 value and set it to a value, and then use break to exit from it.
Using this I managed to do my assignment, but I'm not very satisfied, as I think there might be a better solution.
Is there one?
EDIT: Code since you asked for it.
For loop outside while loop:
for(int x=0;x<ctr-1;x++)
{
for(int y=0;y<maxtrips;y++)
{
EmployeeKilos[x][y] = -9999; // Set all the kilos to -9999 to signify emptiness.
}
}
Inside my main while loop:
for(int x=0;x<ctr-1;x++) // and set it to the log kilometers
{
if(employeenames[x].EmployeeNumber == log.Record)
{
for(int y=0;y<maxtrips;y++)
{
if(EmployeeKilos[x][y] == -9999)
{
EmployeeKilos[x][y] = log.Kilometers;
break;
}
}
}
}
All my code: http://pastebin.com/Zb60mym8
As Dave said, checking for empty values cannot be made more efficient than linear time (O(n)), but my answer focuses on a solution that can prevent having to look for it in the first place.
In general you could iterate the matrix in row-major or column-major mode.
Effectively, you can use a single index that translates to a matrix cell like so
for (size_t i=0; i<ROWS*COLS; ++i)
{
int row = i / ROWS;
int col = i % ROWS;
// work with matrix[row][col]
}
This way you could just store and remember the value of i where you last found the first empty cell, so you don't have to restart from the beginning.
If you're not actually interested in row/col addressing, you could forget about those and just use an output iterator to track your current output location.
Here's a demo using 'iterator' style (borrowing from c++ but perfectly C99)
typedef int data;
typedef data* output;
output add_next(data matrix[ROWS][COLS], output startpoint, data somevalue)
{
if (output < (matrix + ROWS*COLS))
*(output++) = somevalue;
return output;
}
Now you can just say:
add_next(matrix, 42);
add_next(matrix, 9);
NOTE the output iterator thing assumes contiguous storage and therefore cannot be used with so-called jagged arrays
HTH
You can use memset to initialise arrays to a fixed value - it's a bit more efficient and cleaner looking than iterating over the array.
Checking for your 'empty' value can't be done much faster than you are doing it, though. :)
This sounds like you should think about your datatype. Since you are already using structs. why don't you add another int for the last unassigned value so you just loop to it. something like
e.g:
struct t_EmployeeKilos{
int kilos[maxtrips];
int nlast;
} EmployeeKilos[N];
and set nlast whenever you assign a new element in kilos. This way it is O(1).
for(int x=0;x<ctr-1;x++) //
{
if(employeenames[x].EmployeeNumber == log.Record)
{
EmployeeKilos[x].kilos[EmployeeKilos[x].nlast] = log.Kilometers;
EmployeeKilos[x].nlast++;
}
}

verify each element to one other in a array pointer

C Experts,
I have an array of pointers to strings. I need to compare each array element with all other array elements and throw error if they are same. Here is the piece of code I have written and got stuck. Please help me.
# define FOUND 1
# define NOTFOUND 0
int k,flag,a;
char cmp_string[10]; //used to get one array element to compare with all other array elements
char *values[]={010,020,030,040}; //valid case that's how it should be
char *vales[]={010,020,020,030}; wrong or throw error because in array i should have only unique values
int size=4;
for(k=0; k<=size;k++){
strcpy(values[k],cmp_string);
flag=NOTFOUND;
int counter=k+1;
for(int n=counter;n<=size;n++)
{
a=((strcmp(values[n],cmp_string) || (strcmp(values[k-1],cmp_string)))
// stuck here what if k value is 2 I wont be able to compare with zero or first element of array.
if(a==0){
throw error same name for the operation
flag=FOUND;
break;
}
}//for int n;
}//for int k;
if(flag==NOTFOUND){
True or PASS
}
}
Quick solution: sort the array (using e.g. the builtin qsort function), then scan it comparing adjacent elements; if two are the same, you have a repetition.
You can also know before completing the sort that you have duplicates if in the comparison function you find that the two compared items are the same.
If I understand your question correctly, you're trying to turn strcmp into something that returns nonzero if the strings are the same and zero otherwise:
a = (strcmp(whatever) != 0) || (strcmp(whatever else) != 0);

problem with array elements in awk not being stored

I've been using awk to process hourly weather data, storing 10 arrays with as much as 8784 data elements. If an array is incomplete, i.e., stops at 8250, etc., after the "END" command I fill the remaining array elements with the last available value for the array. However, when I then print out the complete arrays, I get 0's for the filled values instead. What's causing this?? Does awk have a limit in the array size that's preventing it from filling the arrays? Following is a snippet of the awk program. In the two print statements, the first time the array elements are filled, but the second time they're empty.
Any help is appreciated because this problem is holding up my work.
Joe Huang
END{
if (lastpresstime < tothrs)
{
diffhr = tothrs - lastpresstime
for (i=lastpresstime+1;i<=tothrs+1;i++)
{
xpressinter[i]=diffhr
xpressrecords[i]=diffhr
xipress[i]=lastpress
xpressflag[i]="R"
printf("PRS xipress[%4d] =%6.1f\n",i,xipress[i]) > "ncdcfm3.prs"
printf(" xipress[%4d] =%6.1f%1s\n",i,xipress[i],xpressflag[i])
}
for (i=1;i<=tothrs+1;i++) printf("PRS xipress[%4d] =%6.1f\n",i,xipress[i])
}
~
I don't have the rep to edit your post, but here's the formatted code:
END {
if (lastpresstime < tothrs) {
diffhr = tothrs - lastpresstime
for (i=lastpresstime+1;i<=tothrs+1;i++) {
xpressinter[i]=diffhr
xpressrecords[i]=diffhr
xipress[i]=lastpress
xpressflag[i]="R"
printf("PRS xipress[%4d] =%6.1f\n",i,xipress[i]) > "ncdcfm3.prs"
printf(" xipress[%4d] =%6.1f%1s\n",i,xipress[i],xpressflag[i])
}
for (i=1;i<=tothrs+1;i++)
printf("PRS xipress[%4d] =%6.1f\n",i,xipress[i])
}
}
Note that I added a matching brace at the end.
I don't see any inherent problems in the code, so like jhartelt, I have to ask - are all of the variables properly defined? We can't tell from this sample how lastpresstime, tothrs, and lastpress get their values. In particular, if lastpress isn't, you'll get exactly the behavior you described. Note that if you have misspelled it, it will be an undefined variable and therefore use the default value of 0.
With respect to William Pursell's comment, there should also be no difference in the output of xipress[i] between the three printfs (for lastpresstime<i).
As 0 is the default value for an unknown/unused numerical variable, I would ask if you are sure, that there is no mistype in the variable names used in the END block?

Resources