简体   繁体   中英

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 it = 0;

            while (--argc > 0 )
            {
                    *(++stack) = atoi(*++argv);     
                    printf( "%d \t %d \n", ++it, *stack );
            }

            delete stack;                   
            return 0;
    }

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

What's more I get error connected with delete operator munmap_chunk(): invalid pointer

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;
}

Your code would be clearer (and correct) if you used array indexing instead of advancing pointers:

#include <cstdlib>
#include <cstdio>

using namespace std;

main( int argc, char **argv ) 
{
    int *stack = new int[argc];
    for( int it = 1; it < argc; ++it )
    {
        stack[it] = atoi(argv[it]);     
        printf( "%d \t %d \n", it, stack[it] );
    }

    delete[] stack;                   
    return 0;
}

No idea why you want to have unused stack[0] , though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM