How to declare the size of an array at runtime in C?

前端 未结 5 1117
我在风中等你
我在风中等你 2021-01-17 17:19

I basically want to the C of equivalent of this (well, just the part with the array, I don\'t need the class and string parsing and all that):

public class E         


        
5条回答
  •  渐次进展
    2021-01-17 17:39

    Unfortunately, many of the answers to this question, including the accepted one, are correct but not equivalent to the OP's code snippet. Remember that operator new[] calls the default constructor for every array element. For POD types like int that do not have a constructor, they are default-initialized (read: zero-initialized, see §8.5 ¶5-7 of The C++ Standard).

    I just exchanged malloc (allocate uninitialized memory) for calloc (allocate zeroed memory), so the equivalent to the given C++ snippet would be

    #include   /* atoi, calloc, free */
    
    int main(int argc, char *argv[]) {
        size_t size = atoi(argv[1]);
        int *foo;
    
        /* allocate zeroed(!) memory for our array */
        foo = calloc(sizeof(*foo), size);
        if (foo) {
            /* do something with foo */
    
            free(foo); /* release the memory */
        }
    
        return 0;
    }
    

    Sorry for reviving this old question but it just didn't feel right to leave without a comment (which I do not have the required rep for) ;-)

提交回复
热议问题