首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

怎么动态生成不定长度的数组

2012-10-23 
如何动态生成不定长度的数组C/C++ codeclass Gobang {public:Gobang(unsigned short int r, unsigned shor

如何动态生成不定长度的数组

C/C++ code
class Gobang {public:    Gobang(unsigned short int r, unsigned short c):row(r),column(c){        _init_board();    }private:    void _init_board() {        for(int i=0; i<row; i++) {            for(int s=0; s<column; s++) {            }        }    }    const unsigned short int row;    const unsigned short int column;    unsigned short int **board;};Gobang g(8,8);

如上图,通过向类传递参数g(8, 8),生成一个board[8][8]的数组,该怎么做,谢谢

[解决办法]
C/C++ code
//在堆中开辟一个4×5的二维int数组#include <stdio.h>#include <malloc.h>int **p;int i,j;void main() {    p=(int **)malloc(4*sizeof(int *));    if (NULL==p) return;    for (i=0;i<4;i++) {        p[i]=(int *)malloc(5*sizeof(int));        if (NULL==p[i]) return;    }    for (i=0;i<4;i++) {        for (j=0;j<5;j++) {            p[i][j]=i*5+j;        }    }    for (i=0;i<4;i++) {        for (j=0;j<5;j++) {            printf(" %2d",p[i][j]);        }        printf("\n");    }    for (i=0;i<4;i++) {        free(p[i]);    }    free(p);}//  0  1  2  3  4//  5  6  7  8  9// 10 11 12 13 14// 15 16 17 18 19
[解决办法]
C/C++ code
//在堆中开辟一个4×5的二维int数组#include <stdio.h>#include <malloc.h>int **p;int i,j;void main() {    p=(int **)malloc(4*sizeof(int *));    if (NULL==p) return;    for (i=0;i<4;i++) {        p[i]=(int *)malloc(5*sizeof(int));        if (NULL==p[i]) return;    }    for (i=0;i<4;i++) {        for (j=0;j<5;j++) {            p[i][j]=i*5+j;        }    }    for (i=0;i<4;i++) {        for (j=0;j<5;j++) {            printf(" %2d",p[i][j]);        }        printf("\n");    }    for (i=0;i<4;i++) {        free(p[i]);    }    free(p);}//  0  1  2  3  4//  5  6  7  8  9// 10 11 12 13 14// 15 16 17 18 19 

热点排行