Samuel Samuel - 3 months ago 19
C Question

expected identifier or '(' in C

My name is Samuel and I have recently started following the CS50 course on Edx. I'm stuck on the second problem set as when I try to compile my code, this message comes up:

expected identifier or '(' in C


If you need my code, here it is:

int main (int argc, string argv[])

int key;

{

if (argc != 2)
{
printf("error\n");
}
else
{
key = atoi(argv[1]);

if (key == 0 || key < 0)
{
printf("error");
}
else
{
printf("%i\n", key);
}
}


}


If there is anything else wrong with my code, could you please hint it for me? Thank you,
Samuel

Answer

Move the declaration int key inside the brackets of main.

Then change the string argv[] argument of main to char* argv[]. string argv[] is simply not correct for a main signature.

You also need to include stdio.h and stdlib.h.

Your code would look like this:

#include <stdio.h>
#include <stdlib.h>

int main (int argc, char* argv[])
{
    int key;

    if (argc != 2)
    {
        printf("error\n");
    }
    else
    {
        key = atoi(argv[1]);

        if (key == 0 || key < 0)
        {
            printf("error");
        }
        else
        {
            printf("%i\n", key);
        }
    }
}

Verified with Coliru