Jectson
Jectson

Reputation: 79

char arrays in C and compare

I've got some problems with char arrays in C.

I've got two arrays:

char history[10][80];
char *args[80];

And I also got a char inputBuffer[80] (this contains one string). What I would like to do is to find out if the value in *args exists in history.

I fill up history like this (histCount is between 0 and 10).

for(j=0; j<MAX_LINE; j++)
{
    history[histCount][j] = inputBuffer[j];
}

What I can't figure out is how I can loop through history to see if it matches args[].

  1. Example If args[0] == 'romeo' and history[3][0] == 'r' then match.
  2. If args[0] == 'selfie' and history[7][0] == 's' then match.

My first idea was to do something like this, but it doesn’t seem to work

for(k=0; k<10; k++) {
    if(args[1] == history[k]) {
        printf("FOUND!!\n");
    }
}

Any help would be greatly appreciated.

Upvotes: 1

Views: 161

Answers (2)

Emz
Emz

Reputation: 1280

I am not 100% sure I understand. args[0] is a pointer, which can be interpreted as a string. Which is not what you want in your example. You want args[0] to be a single char.

int main ( void ) {
    char history[10][80]
    char *args[80]

    int i, j, k;

    // filling
    for (i = 0; i < MAX_LINE; ++i) {
        history[histCount][i] = inputBuffer[i]; // this can be achieved with strcpy();
    }

    for (i = 0; i < 10; ++i) {
        for (j = 0; j < 80; ++j) {
            for (k = j; k < 80; ++k) {
            if (history[i][j] == args[0][k]) {
                printf ("FOUND!!");
                return true;
            }
        }
    }
}

What it does is initiating history as a 2D char array and args as a char array. Then for every row it compares the j index of history with the k index of args.

For the sake of it. A short demo.

        history[0]   args
0,0     a            b
0,1     a            a
0,2     a            d

history[0][0] will find the same character at args[1]

Upvotes: 1

abelenky
abelenky

Reputation: 64672

for(k=0; k<10; k++)
{
    if(strcmp(args[1],history[k]) == 0)
    {
        printf("FOUND!!");
    }
}

Upvotes: 2

Related Questions