Click here to Skip to main content
15,904,156 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Here is a code which i wrote to find duplicates in a string . This code doesn't work. It uses pointers to the string . The pointer *first points to first element of the string and *second to second element . And the two pointers increment and loop thrrough the string and find the duplicates .this is how it is supposed to work ,correct me if i am wrong?


C#
#include<stdio.h>
main()
{
char string[]= "hello";
int len=strlen(string);
char *first=string;
char *second=string+1;
while(first <len-1 && second<len)
{
 if(*first==*second)
 {
  printf("A duplicate found\n");
 }
 first++;
 second++;
}
}
Posted
Comments
Maarten Kools 15-Aug-13 6:01am    
You're comparing your pointer with the length of the string in your while loop (so it'll probably never get into the loop). Make sure your string is null-terminated, and then compare with null.

1 solution

Um.

First and second are both pointers. You are comparing them to integers? Do you think this is a good idea? What do you expect the result to be?

Instead, replace your while loop with a for loop:
C#
#include<stdio.h>
main()
      {
      int i;
      char string[]= "hello";
      int len=strlen(string);
      char *first=string;
      char *second=string+1;
      for (i = 0; i < len - 1; i++)
          {
          if(*first==*second)
              {
              printf("A duplicate found\n");
              }
          first++;
          second++;
          }
      }
 
Share this answer
 
Comments
Member 10200096 15-Aug-13 6:36am    
i thought i might work as i am new to pointers. But also after this change the code does not work .
OriginalGriff 15-Aug-13 6:56am    
"the code does not work."
Is not very helpful as an error message! :laugh:
What is it doing that you didn't expect, or not doing that you did?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900