-2

I am using Microsoft Visual C++ on Windows. I compiled it fine without any errors. However, when I tried to execute it, I got two errors. I read the debugging errors, and I could not understand them. I am somewhat a newbie in C programming.

This code is from Kernighan and Ritchie's textbook on page 61:

#include <ctype.h>

/* atoi: convert s to integer; version 2 */
int atoi(char s[])
{
    int i, n, sign;

    for (i=0; isspace(s[i]); i++) /* skip white space */
        ;
    sign = (s[i] == '-') ? -1: 1;
    if (s[i] == '+' || s[i] == '-') /* skip sign */
        i++;
    for (n=0; isdigit(s[i]); i++)
        n = 10 * n + (s[i] - '0');
    return sign*n;
}

The error:

--------------------Configuration: 3.5 - Win32 Debug--------------------
Linking... LIBCD.lib(crt0.obj) : error LNK2001: unresolved external symbol _main Debug/3.5.exe : fatal error LNK1120: 1 unresolved externals Error executing link.exe. 3.5.exe - 2 error(s), 0 warning(s) 
Seki
  • 11,135
  • 7
  • 46
  • 70
Joseph Lee
  • 529
  • 1
  • 5
  • 10

3 Answers3

5

That's not a complete program. It's just a function. You can't execute it without writing some code to call it.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
3

Every C program needs an entry point and main() provides that.

Please refer to the following:

alk
  • 69,737
  • 10
  • 105
  • 255
Jay
  • 24,173
  • 25
  • 93
  • 141
1

I wonder how you wrote the entire atoi function, without knowing about importance of main(). :) You should write a main() function and call your atoi like this:

#include <stdio.h>//Required for printf used in main()
#include <ctype.h>

/* atoi: convert s to integer; version 2 */
int atoi(char s[])
{
    int i, n, sign;

    for (i=0; isspace(s[i]); i++) /* skip white space */
        ;
    sign = (s[i] == '-') ? -1: 1;
    if (s[i] == '+' || s[i] == '-') /* skip sign */
        i++;
    for (n=0; isdigit(s[i]); i++)
        n = 10 * n + (s[i] - '0');
    return sign*n;
}


/* This is the part you've been missing. */
int main(int argc, char **argv)
{
   printf("%d\n",atoi("-100"));
   return 0;
}

I would also suggest you to: First try to write a hello world program in C++, then move to writing advanced stuff like this.

askmish
  • 6,464
  • 23
  • 42