When i enter strings during execution i get error

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sahil470
    New Member
    • Jul 2010
    • 1

    When i enter strings during execution i get error

    Code:
    
    #include<stdio.h>
    #include<conio.h>
    #include<string.h>
    main()
    {  char (*arr)[5];
    	 int i,j,l;
    	 int flag=0;
     // char *arr[5]={"sahil","abhi","sahil","amit","john"};
      for(i=0;i<5;i++)
      gets(arr[i]);  //the problem is in this code
    
    
      for(i=0;i<5;i++)
      {
    	for(j=i+1;j<5;j++)
    	{     l=strcmp(arr[i],arr[j]);
    	if(l==0)
    	{ printf("duplicate entry");
    	flag=1;
    	break;
    	}
      }
      }
      if(flag==0)
      printf("unique elements");
      }
  • code green
    Recognized Expert Top Contributor
    • Mar 2007
    • 1726

    #2
    what's d errr

    Comment

    • newb16
      Contributor
      • Jul 2008
      • 687

      #3
      Prblm s unntlzd arr. It pnts nwhr.

      Comment

      • Joseph Martell
        Recognized Expert New Member
        • Jan 2010
        • 198

        #4
        arr is a pointer to an array of 5 char elements, not a 5-element array of char pointers.

        I think that what you want to do is
        Code:
        char arr[5][6];
        Right now you are passing in a buffer of 1 char, not a 5-char buffer. The definition for arr that has been commented out accomplishes similar goals.
        Code:
        char *arr[5]={"sahil","abhi","sahil","amit","john"};
        This definition creates arr as a 5-element array of char pointers where char[0] points to a char array containing "sahil", etc.

        I could be wrong though. I haven't limited C/C++ experience.

        Comment

        • Oralloy
          Recognized Expert Contributor
          • Jun 2010
          • 988

          #5
          You never initialized the entries of arr[] to appropriate memory buffers.

          jbm1313 gives a basic solution which will let you accept strings of up to length five.

          Unfortunately its a bad way to implement, as it allocates fixed buffers, but gives you no guarantee of memory safety. If the user enters a string that is too long, it'll propagate down the array with all sorts of interesting results.

          What you really should do is use a length guarded read into an input buffer and then copy from the input buffer to an allocated data buffer and insert that into your data array. Throw an error, if the user's input overruns the input buffer.

          Still, this looks like a homework assignment, so I'll leave the implementation details to you. I hope that our comments above are enough to help you get it done.

          Comment

          Working...