Nithin Nithin - 2 months ago 7
C Question

Using argc to control range of for loop

this is my code. For some reason it gets stuck in an infinite loop(the first for loop). The purpose of this codes it to get a command line arg and the user enters that many arguments and the rest of the program prints the smallest number. Thanks in advance!

#include<stdio.h>

int main(int argc, char *argv[])
{
int array[argc];
int smallest;
for(int i=0; i < argc; i++)
{
printf("Welcome to number comparator!\n");
printf("Enter command line # of numbers(enter delimitater):");
scanf("%d",&array[i]);
}
for(int i=0; i < sizeof(array); i++)
{
if(i == 0)
smallest=array[i];
else if(array[i] < array[i-1])
{
smallest=array[i];
}
}
}
printf("The smallest number is %d", smallest);

return 0;

}


Edit: This is not the same as getting an array of integers from cmd line. the cmd line argument is only to enter how many arguments should be entered. Essentially, if I run ./a.out 5. I enter 5 numbers after that and the smallest should be returned

Answer

You've completely misunderstood how C passes command line arguments. You also have more closing brackets than opening brackets. And your statement order could use some adjustment.

Here's a rework of your code addressing the above issues:

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

int main(int argc, char *argv[])
{
    int length = atoi(argv[1]);

    int array[length];  

    printf("Welcome to number comparator!\n");
    printf("Enter %d number(s): ", length);

    for (int i = 0; i < length; i++)
    {
        (void) scanf("%d", &array[i]);
    }

    int smallest = array[0];

    for (int i = 1; i < length; i++)
    {
        if (array[i] < smallest)
        {
            smallest = array[i];
        }
    }

    printf("The smallest number is %d\n", smallest);

    return 0;
}

This isn't finished code, you still need to do some error checking: make sure a command line value was passed argc > 1; check that the command line value is a number; verify that scanf() sucessfully reads in the numbers; etc.

Comments