what does the following c++ code do
I kno开发者_运维问答w its very naive question, but i am not able to understand what the following code does.
#include <malloc.h>
#define MAXROW 3
#define MAXCOL 4
int main(){
int (*p)[MAXCOL];
p = (int (*)[MAXCOL])malloc(MAXROW*sizeof(*p));
}
Please provide a complete explanation including the type and size of p.
It is just for learning purpose. I am not using this code in any real application.
As far as I can tell, it's gibberish. You probably meant (int(*)[MAXCOL])
.
In C it means that the programmer who wrote it doesn't know how void pointer typecasts work.
In C++ it means that you are allocating an array of arrays. p is an array pointer, so *p is an array of size MAXCOL, and you allocate MAXROW such arrays. The result is a "mangled" 2D array. The avantage of using this rather obscure syntax is that you get a 2D array which has every cell in adjacent memory, something you wouldn't achieve with the more commonly seen pointer-to-pointer dynamic 2D array.
Supposing you meant the uncommented line (the other is the original, which is not valid C)
// p = (*)[MAXCOL]malloc(MAXROW*sizeof(*p));
p = (int(*)[MAXCOL])malloc(MAXROW*sizeof(*p));
my answer is:
In C do not cast the return value of malloc
. It is at best redundant and may hide an error when present. Simply do
p = malloc(MAXROW * sizeof *p);
It's not valid code in C or C++.
So, it doesn't "do" anything at all.
As you can learn from this question, int (*p)[MAXCOL]
is a pointer to an array of MAXCOL integers.
The line p = (int (*)[MAXCOL])malloc(MAXROW*sizeof(*p));
allocates the memory for an array of MAXROW arrays of MAXCOL integers (i.e. two dimensional array), and sets p
to point to it.
I have not compiled the following code, but i think it's valid c++-code:
typedef int[MAXROW][MAXCOL] table;
table *p = new table;
This code is only posible if the dimensions of the array are known at compile-time.
This is the way most c++-prgrammers would define p:
using namespace std;
vector<vector<int> > p;
This allows for a more flexible way of programming.
G, folks, it's been a long time since i have programmed K&R C!
精彩评论