Search code examples
cprogram-entry-pointargvargc

C - Storing main() arguments in an array


I am creating a multithreaded program utilizing bankers algorithm, have all of it hard coded and compiled, but I am having a problem filling the initial available array from user input

#DEFINE NUMBER_OF_RESOURCES 3

int available[NUMER_OF_RESOURCES];       //available will be length of argc i.i number of total resoruces

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

printf("AVAILABLE RESOURCE: \n [");
//Populate Available Resource Array
for (i = 1; i < argc; i++)
{
    available[i-1] = argv[i];
    printf("%d ", available[i]);
}
printf("] \n\n");
}

When executing with: ./a.out 10 7 5

It prints:

[1604031496 1604031499 1604031501 ] 

Solution

  • You can't convert strings to integers with ordinary assignment (you should have gotten a compiler warning about assigning char* to int without a cast). Call atoi() to parse the integers.

    available[i-1] = atoi(argv[i]);