问题
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;
}
回答1:
ArrayList *
createArrayList(int length)
{
ArrayList *r = malloc(sizeof(*r));
if (r == NULL) return NULL;
length = MAX(length, DEFAULT_INIT_LEN); // do not duplicate code. ever.
r->array = calloc(length + 1, sizeof(r->array[0]));
if (r->array == NULL) { free(r); return NULL; } // always check pointers
r->size = 0;
r->capacity = length;
printf("Created new ArrayList of size %d\n", length);
return r;
}
And you probably do not want to allocate length + 1 elements, because you have r->capacity.
回答2:
you must first initialize Arraylist *r:
ArrayList *createArrayList(int length){
int i=0;//index variables
ArrayList *r=malloc(sizeof(ArrayList);
来源:https://stackoverflow.com/questions/21506725/calling-function-with-type-struct-and-returning-pointer-does-not-run