Storing a struct and ints in an array
How would i go about storing structs and also ints in an array?
/*a struct to keep block information*/
struct header{
int freeSpace;
struct header *nextHead;
struct header *prevHead;
};
int myinit(int *array, int size){
array[0] = size;
/*initial block*/
struct header root;
root.freeSpace = size - (sizeof(struc开发者_运维技巧t header));
array[1] = root; /*write the intial block to the array*/
}
Zero element of an array doesn't keep it's size. And you cannot store in one array ints and structs at the same time. You can you use only single object type in array.
For creating a dynamic list you should do the following:
allocate space for the root element(using malloc, don't rewrite it, it rather good)
allocate space for an element and bound it to the root like this:
void constructList() { ... struct header * pRoot = ...; pRoot->previousHead = NULL; struct header * pSecond = ...; pSecond->previousHead = pRoot; pRoot->nextHeader = pSecond; ...
}
keep adding the element
finish construction the list by
pLastElement->nextHeader = NULL;
Then you will be able to run through list checking it's end by comapring the nextHeader pointer with NULL.
You cannot store items of different types in an array. What you can do is create a union type that stores each of the types you are interested in, and create an array of that union type:
union myData
{
int ival;
struct header sval;
...
};
union myData myArr[N];
struct header foo;
...
myArr[0].ival = 100;
myArr[1].sval = foo;
However, I don't think this is the solution you are looking for. It would help to know exactly what you're trying to accomplish here; why are you trying to store a size in one array element and a struct in another?
take a look of this code from here, may be it can help you.
#include<stdlib.h>
#include<stdio.h>
struct list_el {
int val;
struct list_el * next;
};
typedef struct list_el item;
void main() {
item * curr, * head;
int i;
head = NULL;
for(i=1;i<=10;i++) {
curr = (item *)malloc(sizeof(item));
curr->val = i;
curr->next = head;
head = curr;
}
curr = head;
while(curr) {
printf("%d\n", curr->val);
curr = curr->next ;
}
}
regards.
An array is just a block of memory.
You access specific parts of this memory block specifying an offset number. So if you want to reach the block of data at offset 3
it will use the size of the type of the array and multiply it by 3.
This means that the arrays can only contain one datatype, otherwise accessing elements of this array would be a mess.
精彩评论