正在加载图片...
Problem 4:Useful Pointers jArrayT *CreateJaggedArray(int n) { iArrayT *iA; int i; jA GetBlock(sizeof (jArrayT)); jA->sizes GetBlock(n sizeof(int)); jA->rows GetBlock(n sizeof(int *)) jA->nRows n; for (i=0;i n;i++) jA->sizes[i]0; jA->rows [i]NULL; return jA; void SetElement(jArrayT *jArr,int row,int col,int value) { int i,*newRow; if (row 0 row >jArr->nRows) Error("Invalid row index"); /If current row is too small if (jArr->sizes[row]col 1) /Allocate a new row * newRow GetBlock((col 1)*sizeof(int)); /Copy existing elements * for (i=0;i<jArr->sizes[row];i++) newRow[i]jArr->rows [row][i]; /Init the rest to 0 * for i <col;i++) newRow [i]=0; Free old row if necessary if (jArr->rows [row]!NULL) FreeBlock(jArr->rows [row]) /Set new row and its size t/ jArr->rows [row]newRow; jArr->sizes[row]col +1; jArr->rows [row][col]value;4 Problem 4: Useful Pointers jArrayT *CreateJaggedArray(int n) { jArrayT *jA; int i; jA = GetBlock(sizeof (jArrayT)); jA->sizes = GetBlock(n * sizeof(int)); jA->rows = GetBlock(n * sizeof(int *)); jA->nRows = n; for (i = 0; i < n; i++) { jA->sizes[i] = 0; jA->rows[i] = NULL; } return jA; } void SetElement(jArrayT *jArr, int row, int col, int value) { int i, *newRow; if (row < 0 || row >= jArr->nRows) Error(“Invalid row index”); /* If current row is too small */ if (jArr->sizes[row] < col + 1) { /* Allocate a new row */ newRow = GetBlock((col + 1) * sizeof(int)); /* Copy existing elements */ for (i = 0; i < jArr->sizes[row]; i++) newRow[i] = jArr->rows[row][i]; /* Init the rest to 0 */ for ( ; i <= col; i++) newRow[i] = 0; /* Free old row if necessary */ if (jArr->rows[row] != NULL) FreeBlock(jArr->rows[row]); /* Set new row and its size */ jArr->rows[row] = newRow; jArr->sizes[row] = col + 1; } jArr->rows[row][col] = value; }
<<向上翻页向下翻页>>
©2008-现在 cucdc.com 高等教育资讯网 版权所有