Calling Function with type struct and returning pointer does not run

泪湿孤枕 提交于 2019-12-25 03:07:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!