LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Howto compare two strings in C (https://www.linuxquestions.org/questions/programming-9/howto-compare-two-strings-in-c-532258/)

daYz 03-04-2007 01:55 AM

Sorry for the late response, I had some things to do.

Code:

char out[256];
 for(int i = 0; i < strlen(argv[1]); i++)
  out[i] = argv[1][i];

This code works perfectly :)


This seems to go fine:

Code:

char var[10];
strcpy(var, *(argv+1));

When I compare the variable var with another variable the result is always false though, even when the strings are equal.

Code:

    char aap[3] = "aap";
   
    if ( strcmp(aap, var) == 0 ){

          char y = 'y';
          printf("%c", y);}

          else{

          char n ='n';
          printf("%c", n);}

          return 0;}


graemef 03-04-2007 02:16 AM

You didn't allow the string app to have any space for the null terminator... try
Code:

char app[4] = 'aap';

daYz 03-04-2007 02:31 AM

Quote:

Originally Posted by graemef
You didn't allow the string app to have any space for the null terminator... try
Code:

char app[4] = 'aap';

Woohoo! That was the problem indeed. Thanks.

And be carefull over there please.


Quote:

Keep it simple: as simple as possible, but no simpler.
lol

daYz 03-04-2007 02:56 AM

The last thing I don't understand is the memset part from this:

Code:

arg_length = strlen( argv[i] );
arg_copy = malloc( ( arg_length + 1 ) * sizeof( char ) );
memset( arg_copy, 0, (arg_length + 1) * sizeof( char ) );
strncpy( arg_copy, argv[i], arg_length + 1 );

/* Do other stuff... */

free( arg_copy );
arg_length = 0;

Why is the memset part used here? To me it looks like that malloc already did the nessesary work.

graemef 03-04-2007 03:07 AM

It is used to inilisalise the area of memory. When malloc is used it will return a memory location and it could hold anything. This just ensures that the memory is clean.

daYz 03-04-2007 04:10 AM

Quote:

Originally Posted by graemef
It is used to inilisalise the area of memory. When malloc is used it will return a memory location and it could hold anything. This just ensures that the memory is clean.

Thanks graemef.


All times are GMT -5. The time now is 12:52 PM.