c++ - What's wrong with that code? (copying argv[] to array of ints) -


    #include <cstdlib>     #include <cstdio>      main( int argc, char **argv )      {             int *stack = new int[argc];             int = 0;              while (--argc > 0 )             {                     *(++stack) = atoi(*++argv);                          printf( "%d \t %d \n", ++it, *stack );             }              delete stack;                                return 0;     } 

stack[3] should contain integer value argv[3],but doesn't.

what's more error connected delete operator munmap_chunk(): invalid pointer

this code isn't c; it's c++. there 2 options you:

  • compile code c++, or ask/change question target c++ audience instead. expect them complain use of printf...
  • convert code c, easy enough. change <cstdlib> <stdlib.h>, <cstdio> <stdio.h>, new int[argc] malloc(argc * sizeof *stack); , delete stack; free(stack);.

whichever route take, code invokes undefined behaviour; accesses stack out of bounds one, , leaves first element of stack uninitialised i'm sure isn't desired. meant print values after reading them , before incrementing stack, since got wrong you're printing next element within array have of course not yet assigned...

then top off, loop modifies value of stack (that's ++stack does, after all), after loop when use delete you're deleteing reference wasn't created using new... need make sure keep original value of stack, gets deleted, or freed, or whatever...

#include <stdlib.h> #include <stdio.h>  int main( int argc, char **argv ) {         int *stack = malloc(argc * sizeof *stack);         int = 0;         while (--argc > 0){                 stack[it] = atoi(*++argv);                 printf("%d \t %d \n", it, stack[it]);                 it++;         }         free(stack);         return 0; } 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -