Declaring array of int

前端 未结 8 509
-上瘾入骨i
-上瘾入骨i 2020-12-07 13:11

Is there any difference between these two declarations?

int x[10];

vs.

int* x = new int[10];

I suppose th

8条回答
  •  心在旅途
    2020-12-07 13:39

    They are the same as far as both x's point to the first memory address in the array of 10 integers, however very different in that

    int x[10] 
    

    declares the memory in static random access memory, and the keyword 'new' creates them dynamically with the heap, and is about the same as using malloc in c to dynamically create an array.

    Not only that, but (I believe, haven't tested the theory) there is a chance that:

    int* x = new int[10];
    

    could fail, and depending on the compiler, could return an error or a null pointer. If the c++ compiler adheres to ANSI/ISO standards, then it supports a "no-throw" form of new which returns a null if allocation fails, rather than throwing an exception.

    The other difference being that the 'new' operator can be overloaded.

    What I'm not sure of, however, is if either one (in c++) creates a null terminated array. I know that in c, in the compiler I use at least, you must make sure to always append a \0 to any strings or arrays if you expect to be able to iterate over them without overextending the bounds.

    Just my $.02 worth. :)

提交回复
热议问题