我想在爲輸入文件分配多少內存的同時爲結構數組(struct)分配內存。我不確定最明智的做法是什麼。我的結構:爲fgets中的結構數組分配內存
typedef struct sNaryNode {
void* data; // point to each nodes data
unsigned int n; // the number of children
struct sNaryNode **child; // the child list
} NaryNode;
typedef struct {
char *name;
unsigned int utility; // -1, 0, 1
unsigned int probability; // 0-1
} Child;
typedef struct {
unsigned int level;
unsigned int player;
unsigned int nChildren;
Child *children; // The array of structs I am trying to allocate memory to.
} Data;
我曾嘗試以下:
void readData(Data *node) {
FILE *input_file = fopen("data.csv", "r");
if(input_file == NULL) printf("Could not open file\n");
else {
char buf[80];
int n = 0;
while(fgets(buf, 80, input_file)!= NULL) {
// allocate space for new data
Data *node = (Data*)calloc(1, sizeof(Data));
sscanf(buf, " %u, %u, %u, ", &node->level, &node->player, &node->nChildren);
node->children = calloc(node->nChildren, sizeof *node->children);
sscanf(buf, "%u, %u, %s ", &node->children[n].utility, &node->children[n].probability, node->children[n].name);
n++;
}
fclose(input_file);
}
}
int main(void) {
Data *node;
readData(node);
}
這導致分段錯誤,我希望有事情做與錯誤的內存分配。
文件我讀:
level, player, nChildren, utility, probability, name
1, 1, 2, 1 0, 0.50 0.50, "Kom med det første tilbud (anchor)" "Afvent modspilleren kommer med første tilbud"
2, 2, 2, 1 0, 0.50 0.50, "Kom med lavt modtilbud (anchor)"
2, 2, 2, 1 0, 0.50 0.50, "Kom med det første tilbud "anchor"
編輯:GDB告訴我,該段錯誤是從READDATA第二sscanf的陸續上馬。仍然不確定是什麼造成的。
不要改變你的問題的方式,使已經給出的答案不可理解......: -/ – alk