kas
kas

Reputation: 3

How to write a function with argument as a char pointer to return the number of occurence of a certain character in a string

I tried to write a function with an argument as char type pointer to return the number of occurrence of a certain character ,say 'a', in a string.As it needs to be function,I assume main() couldn't be used here.I am using Dev-C++ IDE . My code:

  int countA(char *phrase)
  {
   int count=0;
   for(;*phrase;++phrase)
    {
      if(*phrase=='a')
      count++;
    }
     return count;
  }
   /*void main()
    {

     char a[20];
     int i;
     char *ptr;
     gets(a);
     ptr=a;
     i=countA(ptr);
     printf("i=%d",i);
     getch();
    }*/

It shows error i.e "undefined reference to `WinMain@16'" and"[Error] ld returned 1 exit status". But when i uncomment the main() function ,the whole source code works fine.

Upvotes: 0

Views: 113

Answers (1)

Max Fomichev
Max Fomichev

Reputation: 244

  1. You need some entry point function to link your executable - EntryPoint.
  2. It's more safely to use standard C functions instead of your own, something like:

    int countA(const char *phrase)
    {
        int count = 0;
    
        if (!phrase)
            return count;
    
        while ((phrase = strchr(phrase, 'a'))) {
            phrase++;
            count++;
        }
    
        return count;
    }
    

Upvotes: 1

Related Questions