嗨,我必须为我的大学做一个磁盘模拟。
我有2个文件:
tttfs.h:
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
typedef struct _disk disk;
typedef struct _block block;
struct _block{
uint8_t *unBlock;
};
struct _disk{
int id;
block *diskBlock;
};
tfs_create.c:
#include "tttfs.h"
uint8_t little[4];
int tttfs_create(int size, char *name);
void inttolitend(uint32_t x, uint8_t* lit_int);
int main(){
tttfs_create(7, "disk.tfs");
}
int tttfs_create(int size, char *name){
FILE *f = NULL;
if ((f = fopen(name, "wb"))!=NULL)
{
disk *d = malloc(sizeof(disk));
d->diskBlock = malloc(1024);
d->id = 1;
int i;
for(i = 0; i<size; i++){
printf("%dn", i);
d->diskBlock[i].unBlock = malloc(1024); //I got the segmentation fault here
}
inttolitend(size, little);
for(i = 0; i<4; i++){
d->diskBlock[0].unBlock[i] = little[i];
}
for(i = 0; i<size; i++){
fwrite(&d->diskBlock[i],1024,1,f);
}
}
else
printf("Erreurnn");
return 0;
}
void inttolitend(uint32_t x, uint8_t* lit_int){
lit_int[3] = (uint8_t)x / (256*256*256);
lit_int[2] = (uint8_t)(x % (256*256*256)) / (256*256);
lit_int[1] = (uint8_t)((x % (256*256*256)) % (256*256)) / 256;
lit_int[0] = (uint8_t)((x % (256*256*256)) % (256*256)) % 256;
}
我想在一个文件中写一个数字块(这里是7),所以我对我的磁盘结构的大小做malloc,然后在diskBlock上做一个malloc来制作一个表d->diskBlock[0]。unBlock=malloc(1024);但不是为了更多。我怎么能用我的结构做一个块[大小]?(我不擅长c)
我认为你应该更改这行
d->diskBlock = malloc(1024);
至
d->diskBlock = malloc(sizeof(block) * size);
而且,这个
d->diskBlock[i].unBlock = malloc(1024);
至
d->diskBlock[i].unBlock = malloc(sizeof(uint8_t) * 4);