简体   繁体   中英

How should I write an array that should be saved in heap?

I wrote this till now:

int *p;
p = (int*)malloc(sizeof(int[]));

did I wrong?

I was expecting write a size of the array but without that the programme functions, right?

 int *p; p = (int*)malloc(sizeof(int[]));

did I wrong?

The code is not valid C. int[] is the type name of an incomplete type, and as such, it is not a valid operand of the sizeof operator. This violates a language constraint, so a conforming C implementation is required to emit a diagnostic when it processes the code presented.

I was expecting write a size of the array but without that the programme functions, right?

If you are saying that a program containing the code presented compiles and runs successfully then that is surprising, but ultimately it means nothing. The program has undefined behavior as far as the C language specification is concerned, but that does not mean that a compiler must reject it (after emitting the required diagnostic), or that it must fail at runtime. Other than the diagnostic, the spec doesn't say anything about what will happen -- that's what "undefined behavior" means.

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