I'm trying to do a simple parsing of text with a C program. A function I have written is supposed to check the buffer that has a line of text saved into it and see if this line contains a particular word at BOL.
The input arguments are:
size
: the sizeof(word), calculated before the function is called.buf
: the buffer containing a line from the text being parsed.word
: the word that the function looks for at BOL.
The code is as follows:
#include <stdio.h>
#include <string.h>
int strchk(int size, const char buf[1024], char *word) {
char a[size];
int i;
for (i = 0; i < size - 1; i++) {
a[i] = buf[i];
}
if (strcmp(a, word) == 0)
return 1;
else
return 0;
}
The problem is that for some reason, a word is not being recognized. Previous words have been correctly identified by the same function. Below are two contexts wherein the function is being called, the first one results in a correct identification, the second does not, while the text contains both words at the start of different lines within the text.
char c[] = "|conventional_long_name";
if (strchk(sizeof(c), buf, c)) {
fputs(" conventional_long_name: \"", stdout);
getdata(buf, c, sizeof(c));
}
char d[] = "|official_languages";
if (strchk(sizeof(d), buf, d)) {
fputs(" religion: \"", stdout);
getdata(buf, d, sizeof(d));
}
When I check string a in the strchk()
function for size first, it gives me a size of 20, but if I make it print out the string it tells me it is in fact |official_languagesfici
. When you count the number of characters it's just as long as the previously mentioned |conventional_long_name
, which would suggest some parameter from that function call is at play in the next function call, I just can't figure out where I have made the mistake. Any help would be greatly appreciated.