Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Passing command-line argument of int type always results in 2

+5 votes
asked Aug 23, 2024 by Lucas Grenier (330 points)

Hey! I'm new to OnlineGDB, I'm more accustomed to local IDEs. When I run this code:

#include <stdio.h>

void main(int n) {
    printf("%d", n);
}

with any integer in the "Command line arguments:" box, I get 2 as an output in the console. No matter what the integer is. I've even tried reloading the project. Nothing. Any ideas as to why this might be?

1 Answer

0 votes
answered Aug 28, 2024 by Peter Minarik (101,420 points)
edited Aug 28, 2024 by Peter Minarik

Your main function has the wrong signature. It should receive 2 parameters: argc and argv. The first is the number of arguments passed in from the operating system (including the 1st one, which is the location of the executable) and the 2nd is the array of arguments as strings (const char *).

See the below example:

#include <stdio.h>

int main(int argc, const char * argv[])
{
    printf("I've received %d number of arguments.\n", argc);
    for (int i = 0; i < argc; i++)
    {
        printf("\t%i. argument: %s\n", i, argv[i]);
    }

    return 0;
}

If you want to convert a string to a numeric type, you can use various functions, such as atoi().

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and receive answers from other members of the community.
...