C中的Dyamic双数组

时间:2015-11-14 23:41:24

标签: c arrays

我正在尝试使用malloc来创建一个我不断收到此错误的数组。

严重级代码说明项目文件行 警告C4047'=':'DynamicArray *'的间接水平与'double **'cStudy 19不同

严重级代码说明项目文件行 警告C4133'初始化':不兼容的类型 - 从'int *'到'double *'cStudy 36

 typedef struct
{
double *arrayPointer;
int effectiveSize;
int maximumSize;
} DynamicArray;

void CreateArray(DynamicArray *mArray, int initialSize)
{ 
//TODO: Use malloc to create an array of the initial size.  Assign to   the arrayPointer variable

//TODO: Set effective size to 0 and maximum size to the initial size
mArray->arrayPointer = malloc(initialSize *sizeof(double));
mArray->effectiveSize = 0;
mArray->maximumSize = initialSize;
}

void ExpandArray(DynamicArray * mArray,int newSize) {

    double* newArray;

    mArray->arrayPointer = newArray = (int *)malloc(newSize * sizeof(double));
    memcpy(newArray, &mArray[mArray->effectiveSize], mArray->effectiveSize * sizeof(double));


    free(mArray->arrayPointer);
    //mArray->effectiveSize = 0;
    mArray->maximumSize = newSize;

}

更新了代码,但展开不起作用。

2 个答案:

答案 0 :(得分:2)

此作业

mArray = (double *)malloc(initialSize * sizeof(double *));

应该是

mArray->arrayPointer = malloc(initialSize * sizeof(double));

需要进行一些更改:

  • sizeof应该是double,而不是double*
  • 作业应该是mArray->arrayPointer,而不是mArray本身。
  • C中不需要强制转换为double*

关于施法的观点也适用于这一行:

double* newArray = (int *)malloc(newSize * sizeof(double));

但请注意,ExpandArray可能会使用realloc,而不是普通malloc

答案 1 :(得分:0)

我想通了:D

double * newArray = malloc(sizeof(double)* newSize);
memcpy(newArray, mArray->arrayPointer, newSize * sizeof *newArray);
free(mArray->arrayPointer);
mArray->maximumSize = newSize;
mArray->arrayPointer = newArray;

我只需要更多的咖啡。