質問

Trying to dynamically allocate data from a csv file. I am trying to make an array of structs holding 2d arrays. The problem is that I get a access violation when attempting to allocate memory for the array inside the struct. Marked problem area with comment. Any help is appreciated.

 typedef struct current{

    char **data;

}*CurrentData;

CurrentData getData(FILE *current){

CurrentData *AllCurrentData = malloc(NUM_ITEMS * sizeof(CurrentData));

    /*allocate struct data memory, skipping the first line of data*/
    while ((ch = fgetc(current)) != EOF){
        if (firstNewLine == 0){
            firstNewLine++;
        }
        if (firstNewLine > 0){
            if (ch == '\n'){
                AllCurrentData[newLineCount]->data = malloc(COLUMNS * sizeof(char));  //problem here//
                newLineCount++;
            }
        }
    }
}
役に立ちましたか?

解決

This following line:

CurrentData *AllCurrentData = malloc(NUM_ITEMS * sizeof(CurrentData));

shall be:

CurrentData AllCurrentData = malloc(NUM_ITEMS * sizeof(*CurrentData));

Also replace this:

AllCurrentData[newLineCount]->data

with this:

AllCurrentData[newLineCount].data

Reason: your have typedefed CurrentData to be an pointer to struct current, and you could directly allocate AllCurrentData as an array of struct current.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top