I'm having trouble running the program, there are no warnings or errors popping up in CodeBlocks. The trouble comes when I create an ArrayList struct of pointer type and try to dynamically allocate memory using malloc. I'm using the syntax '->.' I've been at this for hours with no real leads.
#include <stdio.h>
#include <string.h>
#define DEFAULT_INIT_LEN 10//this is in another header file
typedef struct ArrayList{//this is also in another header file
char **array;
int size;
int capacity;
} ArrayList;
int main(void){
ArrayList *test=createArrayList(12);
printf("size: %d capacity: %d\n", test->size, test->capacity);
}
ArrayList *createArrayList(int length){
int i=0;//index variables
ArrayList *r;
if (length>DEFAULT_INIT_LEN){
r->array=malloc(sizeof(char)*(length+1));//create memory for internal array
r->capacity=length;
r->size=0;
for (i=0; i<length; i++)//sets members in the array to NULL
r->array[i]=NULL;
printf("Created new ArrayList of size %d\n", length);
}
else{
r->array=malloc(sizeof(char)*(DEFAULT_INIT_LEN+1));//create memory for internal array
r->capacity=DEFAULT_INIT_LEN;
r->size=0;
for (i=0; i<DEFAULT_INIT_LEN; i++)//sets members in the array to NULL
r->array[i]=NULL;
printf("Created new ArrayList of size %d", DEFAULT_INIT_LEN);
}
return r;
}
And you probably do not want to allocate
length + 1
elements, because you haver->capacity
.you must first initialize Arraylist *r: