Jump to content

Error in checking for duplicate strings?

- - - - -

  • Please log in to reply
2 replies to this topic

#1
surwassu

surwassu

    Newbie

  • Members
  • Pip
  • 1 posts
Hi guys ,
I have been new to C & C++ programming.I got a task to search a string array for duplicate string.If a array consists of a string which is passed as a argument then it should not add the string into the array.

In the following code I have been passing a string(to be search for repetation) as key.
I am going to search in array which is a 2D array declared as char array[100][20].



int  arraySearch(char *key)//string to be searched


{


        int loc=0;

       

                for(loc;loc<=count;loc++) //count :size of array already defined

                  {

                        if((strcmp(array[loc],key))==0)

                           {

                                 break;

                           }

                        else

                           {

                                strcpy(array[count],key);

                                count++;

                           }


                }



return 0;


}






After running this code m getting error like segmentation fault[coer dumped]


Do anyone has idea abt this?
please share it
Warm regards,
Sumit

#2
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others
You need to give us the rest of the code. We have no idea what array or count are. If we can't compile it, we can't test it.

Also, it's not clear what you're trying to do in this function.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#3
Flying Dutchman

Flying Dutchman

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 889 posts
  • Location:::1
Your code crashes because if the key you are searching for is not in the first place (index 0) in your array, it then writes to last element in array (count) and then you increment this count-er and in the next step you write into memory that isn't your array. You first need to search an entire array and only if you hadn't found key, only then you add it to your array (you will have to resize your array with realloc() function call, or make it really big and then just increment count variable).
A conclusion is where you got tired of thinking.
#define class struct    // All is public.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users