Reputation:
I have these structs and I want to initialize the PageTable and PageEntry. I want to create the shape below.
typedef struct PageEntry {
unsigned int page_number;
char mode;
int count, R;
struct PageEntry* next;
} PE;
typedef struct PageTable {
int p_faults, reads, writes, disk_writes, maxFrames, curFrames;
char* algorithm;
struct PE **pe;
} PT;
I want to create a hash table, so I allocate for maxFrames PE*. My PageTable needs to have a pointer to the array and each element has to point to a linked list. Here is my init function:
PT *initialize_Table(int maxFrames, char *algorithm) {
PT *ptr = malloc(sizeof(PT)); //Aloc
ptr->p_faults = 0;
ptr->reads = 0;
ptr->writes = 0;
ptr->curFrames = 0;
ptr->disk_writes = 0;
ptr->maxFrames = maxFrames;
ptr->algorithm = malloc(strlen(algorithm) + 1);
strcpy(ptr->algorithm, algorithm);
ptr->pe = malloc((ptr->maxFrames) * sizeof(PE*));
return ptr;
}
So Ptr->pe must be an array, but it isn't. I get this error:
What should I do ?
Upvotes: 1
Views: 78
Reputation: 2103
No, ptr->pe
is a pointer, not an array. You allocated memory for an array and you can index ptr->pe
as if it was an array. So ptr->pe[i]
is valid, if i
is within range.
The contents of this freshly malloc
ed piece of memory are undefined. Use memset to set it to all zeros, or use calloc
(iso malloc
) to allocate cleared memory.
Arrays in C are second rate citizens. You can declare them , initialize them and query their size with sizeof
, but you can't do anything else with them. For all other purposes an array variable decays (or is treated as) a pointer to the first element.
Upvotes: 1