I’ve been trying to create a tester for my Stack ADT, by dynamically passing in the amount of items to add to the stack. However, when I try passing in an integer, for instance, 22, it assigns the global variable (ITEMS) as 50. If I try something else, the range is between 45, and 55.
My main function is this:
int main(int numArgs, char* numItems[]) {
Stack stack;
if (numArgs == 0) {
printf("Good job, you broke C.\n");
} else if (numArgs == 2) {
int items = (int)*numItems[1];
if(*numItems[1] != ITEMS) {
setItems(items);
}
} else if (numArgs>=3) {
printf("Usage: TestStack <numItems> <-help>\n");
exit(1);
} else if(numItems[1] == "-h" || numItems[2] == "-help") {
printf("numItems - Number of items to add to the stack.\n -h (-help) - Shows this help output.\n");
exit(1);
}
/* test code here*/
}
The assignment function is:
static void setItems(int numItems) {
ITEMS = numItems;
printf("ITEMS IS %d\n",ITEMS);
}
And my global variable is just
int ITEMS = 11; //Default value.
Any reason that I can’t actually get the real value I’m trying to pass in?
Your problem is here:
This will read the
intvalue of the firstcharthat you pass in… Since you pass in22, it will get the ASCII Valule of2which is 50. Refer to this chart (thanks asciitable.com) under Dec 50:What you want to do instead is interpret the whole cstring as an integer, using
atoi:or
strtol: