0

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.

kas
  • 3
  • 3
  • btw, [**don't** use `gets`](https://www.google.co.in/search?q=why+gets+is+dangerous&oq=why+gets+is+&aqs=chrome.1.69i57j0l3.4981j0j1&sourceid=chrome&ie=UTF-8) instead use `fgets` – Grijesh Chauhan Mar 27 '15 at 18:33
  • possible duplicate of [undefined reference to \`WinMain@16'](http://stackoverflow.com/questions/5259714/undefined-reference-to-winmain16) – Dan Oberlam Mar 27 '15 at 18:37
  • c requires a `main`. I'd assume your assignment requires you to write _another_ function (possibly called from `main`) which does the ground work for your task (and which can be reused in different contexts). – SleuthEye Mar 27 '15 at 18:39
  • The problem is that you're trying to compile using MinGW without either a `main` or `WinMain` function. Either compile it to an object file and link it to another object file with one of those functions, or include either of those functions in this .c file. The answer to the question I flagged this as a duplicate of indicates this towards the bottom. – Dan Oberlam Mar 27 '15 at 18:39

1 Answers1

1
  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;
    }
    
Max Fomichev
  • 244
  • 1
  • 13