struct DynamicArray {
int allocated;
int used;
int *array;
}; typedef struct DynamicArray DynamicArray;
DynamicArray * ArrayCreate(int initialSize) {
DynamicArray *array;
(*array).array = (int*)malloc(initialSize*sizeof(int)); //Debugger points this line.
if((*array).array == NULL) {
return NULL;
}
(*array).allocated = initialSize;
(*array).used=0;
return array;
}
I am trying to make my own library for dynamic arrays. Just to learn and improve myself. Please review my code. What am I doing wrong?
You are de-referencing an uninitialized pointer here:
DynamicArray *array; // uninitialized
(*array).array = .... // ooops
You need to make array
point to some memory you can write to. For example
DynamicArray *array = malloc(sizeof(DynamicArray));
First use this :
DynamicArray *array;
array = (DynamicArray *)malloc(sizeof(struct DynamicArray));
array->array = ...
If you don't initialize a point you can't dereference it because its point to NULL.
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.