This code isn't C; it's C++. There are two options for you:
- Compile the code as C++, or ask/change your question to target the C++ audience instead. Expect them to complain about your use of
printf
...
- Convert the code to C, which is easy enough. Change
<cstdlib>
to <stdlib.h>
, <cstdio>
to <stdio.h>
, new int[argc]
to malloc(argc * sizeof *stack);
and delete stack;
to free(stack);
.
Whichever route you take, this code invokes undefined behaviour; it accesses stack
out of bounds for one, and leaves the first element of stack
uninitialised which I'm sure isn't to be desired. You probably meant to print the values after reading them and before incrementing stack
, but since you got that wrong you're printing the next element within your array which you have of course not yet assigned...
Then to top it all off, your loop modifies the value of stack
(that's what ++stack
does, after all), so that after your loop when you use delete
you're delete
ing a reference that wasn't created using new
... You need to make sure you keep the original value of stack
, which gets delete
d, or free
d, or whatever...
#include <stdlib.h>
#include <stdio.h>
int
main( int argc, char **argv ) {
int *stack = malloc(argc * sizeof *stack);
int it = 0;
while (--argc > 0){
stack[it] = atoi(*++argv);
printf("%d \t %d \n", it, stack[it]);
it++;
}
free(stack);
return 0;
}