Just what is wrong with this simple code of mine?

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

main()
{
int i=0, num;
char a[8];
char keyword[8];

system("cls");

      while(i<8)
      {
         num = rand()%3;
 
         if ( num == 0 )
            a[i] = 65 + rand()%26;     /* 65 is the ascii value of A */
         else if ( num == 1)
            a[i] = 97 + rand()%26;     /* 97 is the ascii value of a */
         else
            a[i] = 48 + rand()%10;     /* 48 is the ascii value of 0 */
         i++;
      }
printf("%s", a);     
printf("\n\nEnter the keywords : ");
scanf("%s",&keyword);

if (!strcmp(a, keyword))
{
      printf("The Same!");
      getchar();
      exit(0);
   
}else{
      system("cls");
      main();  
      getchar();      
}
}

I'm using DevC++, and i'm new to this so i don't know if there is any trace... When I used a Borland compiler, i found out that the value of 'a' will double once it passes the strcmp().. Why is this? Here is a pic of the trace...

[IMG]http://i1228.photobucket.com/albums/ee459/Buraian_McBread/1st.jpg[/IMG]

then

[IMG]http://i1228.photobucket.com/albums/ee459/Buraian_McBread/2nd.jpg[/IMG]

Recommended Answers

All 3 Replies

first of all if you intend to use a[] as a string, it should end with '\0' character.

first of all if you intend to use a[] as a string, it should end with '\0' character.

oh.. forgot to carry this statement

a[i] = '\0';

but it's just erasing the unwanted character at the end... My main problem is the value of 'a' has double values

Oh, I solved it now.. just changed the index size from 8 to 9... Will mark this as solved.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.