On Wed, 15 Nov 2006 20:57:00 -0800 (PST)
mahdi heydari <[EMAIL PROTECTED]> wrote:

> i tried this code:
> {
> char A[25][10],B[25];
> for (i=0; i<10; i++)
>   scanf("%s",a[i]);
> scanf("%s",b);
> }

i cannot even see that compiling.

char A[10][25]

you want 10 strings, of length 25. otherwise, although they both contain
the same number of characters in memory you will be accessing the n'th
character in the y'th string... which is harder and none of the c string
functions will work in this fashion.

several people have suggested using strcmp, this is bad. strcmp is
possible to read past then end of the character array if the input was
not null terminated.

to this effect you also have not used a limited string input reader.

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

#define BUFFER 25
#define CONTAINERS 10

int main( int argc, char *argv[] ) {
        char A[CONTAINERS][BUFFER], B[BUFFER];
        int i;

        for( i=0; i<CONTAINERS; i++ ) {
                scanf( "%s", A[i] );
        }
        
        scanf( "%s", B );

        for( i=0 ; i<CONTAINERS; i++ ) {
                if( strncmp( A[i], B, BUFFER ) == 0 ) {
                        fprintf( stdout, "Found match at %d: %s\n", 
                                i, A[i] );
                        return( EXIT_SUCCESS );
                }
        }

        return( EXIT_FAILURE );
}

in this listing the string input is not checked for length. that means
one could overwrite the data in adjacent memory. give it a go yourself.

if we assume the memory is laid out sequentially then the loop's A[i]
will point to some memory that has just been overwritten, and should
rewrite it. but A[i-1] will not be null terminated.

now see the difference in this listing

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

#define BUFFER 25
#define CONTAINERS 10

int main( int argc, char *argv[] ) {
        char A[CONTAINERS][BUFFER], B[BUFFER];
        int i;

        for( i=0; i<CONTAINERS; i++ ) {
                fprintf( stdout, "Enter text %d: ", i );
                fgets( A[i], BUFFER, stdin );
        }
        
        fprintf( stdout, "Enter string to search for: " );
        fgets( B, BUFFER, stdin );

        for( i=0 ; i<CONTAINERS; i++ ) {
                if( strncmp( A[i], B, BUFFER ) == 0 ) {
                        fprintf( stdout, "Found match at %d: %s\n", 
                                i, A[i] );
                        return( EXIT_SUCCESS );
                }
        }

        return( EXIT_FAILURE );
}


-- 
Regards, Ed                      :: http://www.bsdwarez.net
proud python hacker
Every time Mr. T pities a fool, an angel gets its wings. 

Reply via email to